search
HomeJavajavaTutorialJava asynchronous callback mechanism example analysis

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); 
}

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);
    }
}

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);
    }
}

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 - the printed results are as follows:

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

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

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

3. Application scenarios of callbacks

In what scenarios are callbacks currently used more often? Calling from the operating system to developers:

1. The message mechanism of the Windows platform 2. Asynchronously call the WeChat interface and respond to the business logic according to the WeChat return status. 3. Filter in Servlet is based on callback function and needs container support.

Supplement: 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
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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function