Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Java callback mechanism

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how to understand the Java callback mechanism". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Classification of system calls

Calls between application system modules are usually divided into synchronous calls, asynchronous calls, and callbacks.

Synchronous call

Synchronous invocation is the most basic way of calling. The a () method of class A calls the b () method of class B, and the method of class A needs to wait until the method execution of class B is completed. If the method of B is blocked for a long time, it will cause the class A method to fail to execute properly.

Asynchronous invocation

If it takes a long time for A to call BMageB, then you need to consider asynchronous processing so that the execution of B does not affect A. Usually a new thread is created in A to call B, and then the code in A continues to execute.

Asynchronism is usually divided into two situations: first, it can be called directly without the result of the call, such as sending a message notification; second, the result of asynchronous call is required, which can be implemented using Future+Callable in Java.

Callback

From the figure above, we can see that it belongs to a two-way calling mode. The basic idea of the callback is that A calls BJI B and then invokes the callback method provided by A (usually callbakc ()) to notify the result.

Callbacks are usually divided into synchronous callbacks and asynchronous callbacks. Most of the callback cases on the network are synchronous callbacks.

The synchronous callback is similar to the synchronous call. When the code runs to a certain location, if it encounters the code that needs callback, it will wait here and wait for the callback result to return before continuing execution.

The asynchronous callback is similar to the asynchronous call. When the code executes to the code that needs the callback, it does not stop, but continues to execute. Of course, the result of the callback may be returned later.

Synchronous callback instance

Let's take the synchronous callback as an example to explain the Java code implementation of the callback. The whole process simulates the above question-and-answer scenario.

First, define the API to a CallBack to separate the callback function:

Public interface CallBack {void callback (String string);}

A callback method is provided in the CallBack interface to be called on callback.

Then define the person who asks the question Person:

Public class Person implements CallBack {private Genius genius; public Person (Genius genius) {this.genius = genius;} @ Override public void callback (String string) {System.out.println ("received answer:" + string);} public void ask () {genius.answer (this);}}

Since Person needs to provide callback methods, implement the CallBack interface and its methods, which mainly deal with the callback results.

At the same time, because Person calls the method corresponding to Genius, you need to hold a reference to Genius, which is passed in through the constructor.

Define the great god Genius class that answers questions:

Public class Genius {public void answer (CallBack callBack) {System.out.println ("busy with other things..."); try {Thread.sleep (2000); System.out.println ("busy with other things, start calculating...");} catch (InterruptedException e) {e.printStackTrace () } System.out.println ("Genius calculates the answer is: 2"); / / callback tells you callBack.callback ("2");}}

The simulation god is busy, and the thread sleeps for 2 seconds. After the thread is busy, it begins to help calculate the answer. After getting the answer, call the callback method of the CallBack API to call back and notify the result.

Test through the Main method:

Public static void main (String [] args) {Genius genius = new Genius (); Person you = new Person (genius); you.ask ();}

The printing result is as follows:

Busy with other things. After finishing other things, begin to calculate. The genius calculated the answer as: 2 received the answer: 2

The above process implements a synchronous callback function. Of course, programmatically speaking, Person and Genius can be further abstracted and presented in the form of interfaces.

In the code implementation of the above callback mechanism, the core is to pass the this parameter, that is, the caller itself, when the answer method is called.

In essence, callback is an idea and a mechanism. As for how to implement it, how to achieve it elegantly through code and how to achieve high scalability, we need the eight Immortals to cross the sea.

Asynchronous callback instance

The above example demonstrates the synchronous callback, which is obviously affected by the Genius execution time, so you need to wait until the Genius is finished before you can continue to execute the subsequent code in the Person method.

Following improvements on the above example, Person provides a method that supports asynchronous callbacks:

Public void askASyn () {System.out.println ("ask questions for creating a new thread"); new Thread (()-> genius.answer (this)) .start (); System.out.println ("new thread started...");}

Within this method, a new thread is created to handle calls to the Genius#answer method, so that you can skip the blocking of the Genius#answer method and directly perform the following operation (log printing).

Change the called method to askASyn in the main method, and print the result as follows:

Create a new thread and ask for advice. The new thread has been started. Busy with other things. After finishing other things, begin to calculate. The genius calculated the answer as: 2 received the answer: 2

As you can see, the "new thread started..." is printed directly, and then the information received by the Genius#answer method when the log and callback are processed in the callback method is printed.

Semi-Asynchronous based on Future

In addition to the above synchronous and asynchronous processing, there is also a semi-asynchronous processing based on Future between synchronous and asynchronous.

Java can not get the real data immediately after using nio, but first get a "future", which can be understood as postmark or express order. In order to get the real data, we need to constantly check whether the delivery is actually delivered through the express order number "future".

Futures is an abstract concept that represents a value that becomes available at some point. A Future either gets the result of the calculation or gets the exception after the calculation fails.

When do you usually use Future? In general, when performing a time-consuming task, using Future allows the thread to temporarily deal with other tasks and return its results after the long task has been executed.

The scenarios in which Future is often used are: 1. Compute dense scenarios. two。 Deal with a large amount of data. 3. Remote method calls, etc.

Java comes with the Future interface in the java.util.concurrent package, which is executed asynchronously using Executor.

For example, the following code gets a callback Future for each Runnable object passed to the ExecutorService.submit () method, which is used to detect whether it is executed or not, which can be done synchronously waiting for the line processing result to complete.

Public class TestFuture {public static void main (String [] args) {/ / implement a Callable interface Callable c = ()-> {/ / here is the business logic processing / / Let the current thread block for 1 second to see the effect Thread.sleep (1000); return new User ("Zhang San");} ExecutorService es = Executors.newFixedThreadPool (2); / / remember to use submit and execute the Callable object Future fn = es.submit (c); / / be sure to call this method, otherwise executorService.isTerminated () will never be true es.shutdown (). / / the infinite loop waits for the task to be processed. If the task has been processed, isDone returns true while (! fn.isDone ()) {try {/ / the result returned after processing User nt = fn.get (); System.out.println (nt.name) } catch (InterruptedException | ExecutionException e) {e.printStackTrace ();} static class User {private String name; private User (String name) {this.name = name;}

In this case, although a new thread is created for processing, you still need to wait for the result of the processing. The advantage is that batch processing can be divided into several threads at the same time, and finally the results are merged to achieve the purpose of improving processing efficiency.

This is the end of "how to understand the Java callback mechanism". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report