An example analysis of Java asynchronous callback mechanism

  • 2020-06-12 08:59:28
  • OfStack

Java asynchronous callback mechanism

1. What is a callback

Callback, callback. There has to be a call before there is a callback between the caller and the called. So in Baidu Baike, it looks like this:

There is always a definite interface between software modules, which can be divided into three categories: synchronous invocation, callback and asynchronous invocation.

Callbacks are a special kind of call, but the three ways are a little different.

1, synchronous callback, that is, blocking, one-way.

2, callback, that is, two-way (similar to the two gears of a bicycle).

3, asynchronous call, that is, through asynchronous message for notification.

2. Asynchronous callbacks in CS (Java case)

For example, here is a simulated scenario: the client sends msg to the server, and after processing (5 seconds), the server calls back to the client to tell it the processing is successful. The code is as follows:

Callback interface class:


/**
 * @author Jeff Lee
 * @since 2015-10-21 21:34:21
 *  The callback mode - Calls back to the interface class 
 */
public interface CSCallBack {
  public void process(String status);
}

Simulated client:


/**
 * @author Jeff Lee
 * @since 2015-10-21 21:25:14
 *  The callback mode - Simulate the client class 
 */
public class Client implements CSCallBack {

  private Server server;

  public Client(Server server) {
    this.server = server;
  }

  public void sendMsg(final String msg){
    System.out.println(" Client: The message sent is: " + msg);
    new Thread(new Runnable() {
      @Override
      public void run() {
        server.getClientMsg(Client.this,msg);
      }
    }).start();
    System.out.println(" Client: Asynchronous send successful ");
  }

  @Override
  public void process(String status) {
    System.out.println(" Client: Server callback status is: " + status);
  }
}

Simulated server:


/**
 * @author Jeff Lee
 * @since 2015-10-21 21:24:15
 *  The callback mode - Simulate the server class 
 */
public class Server {

  public void getClientMsg(CSCallBack csCallBack , String msg) {
    System.out.println(" Server: The server receives the message sent by the client :" + msg);

    //  The mock server needs to process the data 
    try {
      Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(" The service side : Data processing successful, return to successful status  200");
    String status = "200";
    csCallBack.process(status);
  }
}

The test class:


/**
 * @author Jeff Lee
 * @since 2015-10-21 21:24:15
 *  The callback mode - The test class 
 */
public class CallBackTest {
  public static void main(String[] args) {
    Server server = new Server();
    Client client = new Client(server);

    client.sendMsg("Server,Hello~");
  }
}

Run the test class-print results as follows:

Client: Sends the message Server,Hello~
Client: Asynchronous send successful
Server: The server receives the message sent by the client :Server,Hello~
(The server processing time is simulated here, waiting for 5 seconds)
Server: data processing successful, return success status 200
Client: Server callback status: 200

Analyze the code step by step, and the core is summarized as follows

1. The interface is a method parameter that actually passes in a reference to the implementation class
2. In Client's sendMsg method, the parameter is final, because a new thread can be used by the inner class. That's where asynchrony comes in.
3. Call getClientMsg() of server and pass the parameter to Client itself (corresponding to point 1).

3. Application scenario of callback

What are the scenarios in which callbacks are used most? From operating system to developer call:

1. Message mechanism of Windows platform
2. Asynchronously invoke the WeChat interface and return the response to the business logic according to the status of WeChat.
3. Filter(filter) in Servlet is based on callback function and needs container support.

Supplement: The difference between Filter(filter) and Interceptor(interceptor) is that the interceptor is based on Java's reflection mechanism and is independent of the container. But the same goes for the callback mechanism.

In summary, this design increases the flexibility of the program by allowing the underlying code to call subroutines that are defined at a higher level (implementation level).

4. Model comparison

As mentioned above, Filter and Intercepter do the same thing. There are also similarities between the interface callback mechanism and the design-observer pattern:

Observer mode:

GOF says - "Defines a one-to-many dependency of an object, so that when the state of an object is sent to change, all dependent objects are notified and updated." It is a pattern, implemented by means of an interface callback, that is, it is a representation of a callback.

Interface callback:

The difference with the observer pattern is that it is a principle rather than an implementation.

Their experiences in 5.

Summarize the 4 steps:

The mechanism is the principle.
The pattern is the embodiment.
Remember specific scenarios, common patterns.
And then go into the principle.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: