Using the Observer pattern implementation thread to callback the result of the calculation to multiple objects __java_concurrency

Source: Internet
Author: User
Tags thread class

The third chapter of Java Network programming threads that use callback methods to return information from a thread to an object. For example, if more than one object is interested in the results of a thread's calculations, the thread can save a list of objects to be recalled. A specific object can be added to this list by calling a method of the thread class to complete the registration, indicating that he is interested in the results. If there are instances of multiple classes interested in the result, you can define a new observer interface (interface), all of which will implement this new interface. This observer interface (interface) declares the callback method. The above is a typical application scenario for the Observer pattern.

The above requirements are then implemented.

1. Observer Interface

Declaring callback method update

Interface Observer {
    void update (byte[] digest);

Where the notifying person is the member variable

public class InstanceCallbackDigestUserInterface01 implements Observer {

    static Logger Logger = Loggerfactory.getlogger (instancecallbackdigestuserinterface01.class);

    private String filename;
    Private byte[] Digest;

    Public InstanceCallbackDigestUserInterface01 (String filename) {
        this.filename = filename;

    @Override public
    String toString () {
        string result = filename + ":";
        if (digest!= null) {Result
            = Datatypeconverter.printhexbinary (digest);
        } else {result
            = "Digest Not AV Ailable ";
        return result;

    @Override public
    void Update (byte[] digest) {
        this.digest = digest;
        It just shows the summary, but a more powerful class can also do other things
        //such as storing the digest in a field, using it to start another Chan Cheng, or doing a further calculation on it. (this.tostring ());

3. Interested observer INSTANCECALLBACKDIGESTUSERINTERFACE02 and new thread task Savedatabase
public class InstanceCallbackDigestUserInterface02 implements Observer {

    Logger Logger = Loggerfactory.getlogger ( Instancecallbackdigestuserinterface02.class);

    Byte[] digest = null;

    @Override public
    void Update (byte[] digest) { (' interface02 get this digest ');
        This.digest = digest;
        Executorservice exec = Executors.newcachedthreadpool ();
        Exec.submit (New Savedatabase (Digest));

Class Savedatabase implements Runnable {

    Logger Logger = Loggerfactory.getlogger (savedatabase.class);
    Private byte[] Digest;

    Public Savedatabase (byte[] digest) {
        this.digest = digest;

    @Override public
    Void Run () {
        String s = datatypeconverter.printhexbinary (digest); (s);

4. Instancecallbackdigest of the notifying person


Saves a list of objects to callback callback. A specific object can be added to this list by calling the Attach method to complete the registration

public class Instancecallbackdigest implements Runnable {Logger Logger = Loggerfactory.getlogger (instancecallbackdig

    private String filename;

    Private linkedhashset<observer> callback = new linkedhashset<> ();
    Public instancecallbackdigest (String filename) {this.filename = filename;
    public void Attach (Observer Observer) {callback.add (Observer);
    public void Detach (Observer Observer) {callback.remove (Observer);
            @Override public void Run () {try {fileinputstream in = new FileInputStream (filename);
            MessageDigest sha = messagedigest.getinstance ("SHA-256");
            Digestinputstream din = new Digestinputstream (in, SHA);  while ( ()!=-1);
            Read entire file din.close ();
            Byte[] Digest = Sha.digest ();
   for (Observer o:callback) { ("callback Update");             O.update (Digest); catch (IOException |
        NoSuchAlgorithmException ex) {System.err.println (ex);
5.       Test Class
public class Test {static Logger Logger = Loggerfactory.getlogger (Test.class);  public void Calculatedigest (String filename, linkedhashset<observer> callback) {Instancecallbackdigest CB =
        New instancecallbackdigest (filename);
        Register for (Observer o:callback) {Cb.attach (o);
        Thread t = new Thread (CB);
    T.start ();
        @org. Junit.test public void Test () { ("main thread");
string[] STRs = new string[]{"Bw01.txt", "Pom.xml"};
        string[] STRs = new string[]{"Bw01.txt"}; for (String filename:strs) {//register InstanceCallbackDigestUserInterface01 d = new Instancecallback
            DIGESTUSERINTERFACE01 (filename);
            InstanceCallbackDigestUserInterface02 interface02 = new InstanceCallbackDigestUserInterface02 ();
            Linkedhashset<observer> callback = new linkedhashset<> (); callback.aDD (d);

            Callback.add (INTERFACE02);

            Started the thread calculatedigest (filename, callback);
            How do I inform the mainline Cheng Zi thread end?
            try {TimeUnit.SECONDS.sleep (3l);
            catch (Interruptedexception e) {e.printstacktrace ();
6. Class Diagram

7. Operating Results

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.