Home Java javaTutorial Java asynchronous callback mechanism

Java asynchronous callback mechanism

Dec 05, 2016 am 11:51 AM
java

1. What is a callback?

Callback, callback. There must be a call first before there is a callback between the caller and the callee. So in Baidu Encyclopedia it is like this:

There are always certain interfaces between software modules. In terms of calling methods, they can be divided into three categories: synchronous calls, callbacks and asynchronous calls.
Callback is a special kind of call, and the three methods are a little different.

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

2. Callback, that is, two-way (similar to two gears on a bicycle).

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

2. Asynchronous callback in CS (java case)

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

Callback interface class:

public interface CSCallBack {
    public void process(String status);
}
Copy after login

Simulated client:

public class Client implements CSCallBack {

    private Server server;    
      public Client(Server server) {        
      this.server = server;
    }    
      public void sendMsg(final String msg){
        System.out.println("客户端:发送的消息为:" + msg);        
             new Thread(new Runnable() {            
             @Override
            public void run() {
                server.getClientMsg(Client.this,msg);
            }
        }).start();
        System.out.println("客户端:异步发送成功");
    }    
             @Override
    public void process(String status) {
        System.out.println("客户端:服务端回调状态为:" + status);
    }
}
Copy after login

Simulated server:

public class Server {
    public void getClientMsg(CSCallBack csCallBack , String msg) {
        System.out.println("服务端:服务端接收到客户端发送的消息为:" + msg);        
        // 模拟服务端需要对数据处理
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("服务端:数据处理成功,返回成功状态 200");
        String status = "200";
        csCallBack.process(status);
    }
}
Copy after login

Test class:

public class CallBackTest {
    public static void main(String[] args) {
        Server server = new Server();
        Client client = new Client(server);
        client.sendMsg("Server,Hello~");
    }
}
Copy after login

Run the test class - the printed results are as follows:

客户端:发送的消息为:Server,Hello~
客户端:异步发送成功
服务端:服务端接收到客户端发送的消息为:Server,Hello~
(这里模拟服务端对数据处理时间,等待5秒)
服务端:数据处理成功,返回成功状态 200客户端:服务端回调状态为:200
Copy after login

Analyze the code step by step, The core summary is as follows

1、接口作为方法参数,其实际传入引用指向的是实现类
2、Client的sendMsg方法中,参数为final,因为要被内部类一个新的线程可以使用。这里就体现了异步。
3、调用server的getClientMsg(),参数传入了Client本身(对应第一点)。
Copy after login

3. Application scenarios of callbacks

In what scenarios are callbacks currently used more often? From operating system to developer call:

1、Windows平台的消息机制
2、异步调用微信接口,根据微信返回状态对出业务逻辑响应。
3、Servlet中的Filter(过滤器)是基于回调函数,需容器支持。
Copy after login

Addition: The difference between Filter and Interceptor is that the interceptor is based on Java’s reflection mechanism and has nothing to do with the container. But it is similar to the callback mechanism.

In short, this design allows the underlying code to call subroutines defined by the higher level (implementation layer), which enhances the flexibility of the program.

4. Mode Comparison

As mentioned above, Filter and Intercepter have the same purpose. In fact, the interface callback mechanism is also similar to a design pattern - the observer pattern:

Observer pattern:

GOF said - "Define a one-to-many dependency relationship of an object. When the state of an object changes, it sends At this time, all objects that depend on it are notified and updated. "It is a pattern that is implemented through the interface callback method, that is, it is a manifestation of callback.

Interface callback: The difference between

and the observer pattern is that it is a principle rather than a specific implementation.

5. Experience

Summary in four steps:

The mechanism is the principle.
Pattern is manifestation.
Remember specific scenarios and common patterns.
Then understand the principles in depth.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles