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 realize the callback mechanism in Java

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "how to implement the callback mechanism in Java". 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!

Calls between modules

In an application system, no matter what language is used for development, there must be calls between modules, which can be made in several ways:

(1) synchronous call

Synchronous invocation is the most basic and simplest way of calling, the method a () of class A calls the method b () of class B, waiting for the completion of the execution of the method b (), and the method a () continues to go down. This method of calling is suitable for the case that the execution time of the method b () is not long, because if the execution time of the method b () is long or blocks directly, the rest of the code of the method a () cannot be executed, which will block the whole process.

(2) Asynchronous call

Asynchronous invocation is a way of calling to solve the problem that synchronous calls may block and cause the whole process to get stuck. The method a () of class A calls the method b () of class B through a new thread, and the code then executes directly, so that no matter how long it takes for method b () to execute, it does not block the execution of method a ().

But in this way, because method a () does not wait for the execution of method b () to be completed, when method a () requires the execution result of method b () (depending on the specific business, some businesses, such as starting an asynchronous thread to send a Wechat notification and refreshing a cache, are not necessary), the execution result of method b () must be monitored in a certain way.

In Java, you can do this using Future+Callable, which can be done in my article Java Multithreading 21: CyclicBarrier, Callable, Future, and FutureTask of other components under Multithreading.

(3) callback

1. What is a callback?

Generally speaking, there is a certain invocation relationship between modules, which can be divided into three types: synchronous invocation, asynchronous invocation and callback. Synchronous call is a blocking call, that is, it is called by writing the function name of function B in the function body of function A, so that the code of the corresponding function B in memory can be executed. Asynchronous invocation is a mechanism similar to messages or events that solves the problem of synchronous blocking. For example, after A notifies B, they each go their own way and do not affect each other. Like synchronous invocation, after A notifies B, A does not continue to walk until B is finished. Callback is a two-way invocation mode, that is, when the called interface is called, it will also call each other's interface, for example, A will call Bline B and then An after execution.

2. The purpose of callback

Callback is generally used for inter-layer cooperation. The upper layer installs the function of this layer in the lower layer, which is the callback, and the lower layer triggers the callback under certain conditions. For example, as a driver, it is a bottom layer. When he receives a data, in addition to completing the processing work of this layer, he will also make a callback and send the data to the upper application layer for further processing, which is very common in hierarchical data communication.

"callback" in multithreading

In Java multithreading, the return value after thread execution can be obtained by combining callable with future or futuretask. The implementation method is to call the call method of callable through the get method to get the return value.

In fact, this method is not a callback in nature, but requires the caller to actively call back the caller's interface after the task is completed. In this case, the caller actively uses the get method to block to get the return value.

Callback in public class multithreading {/ / here we simply use future and callable to implement public static void main (String [] args) throws ExecutionException after thread execution, InterruptedException {ExecutorService executor = Executors.newCachedThreadPool (); Future future = executor.submit (new Callable () {@ Override public String call () throws Exception {System.out.println ("call") TimeUnit.SECONDS.sleep (1); return "str";}}); / / Manual blocking calls get to get the return value through the call method. System.out.println (future.get ()); / / needs to be shut down manually, otherwise threads in the thread pool will continue to execute. Executor.shutdown (); / / uses futuretask as both thread execution unit and data request unit. FutureTask futureTask = new FutureTask (new Callable () {@ Override public Integer call () throws Exception {System.out.println ("dasds"); return new Random () .nextInt ();}}); new Thread (futureTask) .start (); / / blocking to get the return value System.out.println (futureTask.get ()) } @ Testpublic void test () {Callable callable = new Callable () {@ Override public Object call () throws Exception {return null;}}; FutureTask futureTask = new FutureTask (callable);}} Java callback mechanism

I have occasionally heard of the callback mechanism, and I can vaguely understand something, but I was dumbfounded when I asked myself to write a simple example program. With more work experience, I often hear callbacks used here and there, so it's time for me to study the Java callback mechanism. There are a lot of articles about Java callback on the Internet, but after reading it, I don't know what to say, especially when I see two steps to grab other people's code. So I decided to write an article about the Java mechanism, in order to facilitate you and yourself to learn more about the Java callback mechanism.

First of all, what is a callback function, to quote the Baidu encyclopedia explanation: a callback function is a function called through a function pointer. If you pass the pointer (address) of a function to another function as an argument, when the pointer is used to call the function it points to, we say this is a callback function. The callback function is not called directly by the implementer of the function, but by another party when a specific event or condition occurs, and is used to respond to the event or condition [2].

I'm sorry, I've read the above explanation several times, but I don't understand the profound mystery. I'm sure you are the same for some readers. Just talking and not practicing fake tricks, we still understand the context in terms of actual combat.

Example 1: synchronous call

This article takes the underlying service BottomService and the upper layer service UpperService as examples, and invokes the underlying service using the upper service. The overall execution process is as follows:

Step 1: execute UpperService.callBottomService ()

Step 2: execute BottomService.bottom ()

Step 3: execute UpperService.upperTaskAfterCallBottomService ()

1.1 synchronous call code

Synchronous call sequence diagram:

Synchronous call sequence diagram

1.1.1 underlying service class: BottomService.java

Package synchronization.demo;/*** Created by lance on 2017/1/19.*/public class BottomService {public String bottom (String param) {try {/ / simulates the underlying processing time, and the upper service needs to wait for Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} return param + "BottomService.bottom () execute-- >";}}

1.1.2 Upper layer service interface: UpperService.java

Package synchronization.demo;/*** Created by lance on 2017/1/19.*/public interface UpperService {public void upperTaskAfterCallBottomService (String upperParam); public String callBottomService (final String param);}

1.1.3 upper layer service interface implementation class: UpperServiceImpl.java

Package synchronization.demo;/*** Created by lance on 2017/1/19.*/public class UpperServiceImpl implements UpperService {private BottomService bottomService;@Overridepublic void upperTaskAfterCallBottomService (String upperParam) {System.out.println (upperParam + "upperTaskAfterCallBottomService () execute.");} public UpperServiceImpl (BottomService bottomService) {this.bottomService = bottomService;} @ Overridepublic String callBottomService (final String param) {return bottomService.bottom (param + "callBottomService.bottom () execute->");}}

1.1.4 Test test class: Test.java

Package synchronization.demo;import java.util.Date;/*** Created by lance on 2017/1/19.*/public class Test {public static void main (String [] args) {BottomService bottomService = new BottomService (); UpperService upperService = new UpperServiceImpl (bottomService); System.out.println ("= callBottomService start =:" + new Date ()); String result = upperService.callBottomService ("callBottomService start-- >") / / upperTaskAfterCallBottomService execution must wait for callBottomService () to call the BottomService.bottom () method to return before executing upperService.upperTaskAfterCallBottomService (result); System.out.println ("= callBottomService end =:" + new Date ());}}

1.1.5 output result:

= callBottomService start =: Thu Jan 19 14:59:58 CST 2017callBottomService start-- > callBottomService.bottom () execute-- > BottomService.bottom () execute-- > upperTaskAfterCallBottomService () execute.= callBottomService end =: Thu Jan 19 15:00:01 CST 2017

Note the output result:

In synchronous mode, Test calls callBottomService () to wait for the end of execution, and then performs the next step, that is, the end of execution. The callBottomService start execution time is Thu Jan 19 14:59:58 CST 2017 and the execution end time is Thu Jan 19 15:00:01 CST 2017, which takes 3 seconds, which is consistent with the simulation time, that is, 3000 milliseconds.

Example 2: from shallow to deep

A few days ago, the company interview asked the question of java callback, because there is not much research in this area, so the answer is ambiguous, this time specially to tutoring. Looking at the online callback explanations and examples, they are all so roundabout that it takes a long time to come back. In fact, callback is a very simple mechanism. Let me explain it in simple language: suppose there are two classes, An and B, there is a method a () in An and a method b () in B; the method b () in B is called in A, and the method a () is called in method b (), which implements the functions of both b () and a () methods.

Doubt: why is it so troublesome? I can just call the a () method under the B.b () method in class A.

Answer: callbacks are more like a convention, that is, if I call the b () method, then I have to call back instead of displaying the call

1. Callback of Java-shallow

Let's use an example to explain: Xiao Ming and Xiao Li agreed to have breakfast together, but Xiao Li got up a little late and had to wash first. After Xiao Li finished washing, he told Xiao Ming to go to dinner together. Xiaoming is class An and Xiao Li is class B. The event of going to dinner together is method a (), and Xiao Li to wash is method b ().

Public class XiaoMing {/ / Xiao Ming and Xiao Li have dinner together public void eatFood () {XiaoLi xl = new XiaoLi (); / / A calls the method xl.washFace () of B;} public void eat () {System.out.print ("Xiao Ming and Xiao Li go to eat lobster together") }} so how to let Xiao Li inform Xiao Ming to eat together after washing? public class XiaoMing {/ / Xiao Ming and Xiao Li have dinner together public void eatFood () {XiaoLi xl = new XiaoLi (); / A calls the method xl.washFace () of B; eat ();} public void eat () {System.out.print ("Xiao Ming and Xiao Li go to eat lobster together");}}

But as mentioned above, this is not a callback function, so it can't be like this. The correct way is as follows.

Public class XiaoLi {/ / Xiao Li public void washFace () {System.out.print ("Xiao Li wants to wash"); XiaoMing xm = new XiaoMing (); / / B calls A's method xm.eat (); / / after washing, let's go to dinner}}

In this way, you can implement washFace () as well as eat (). After Xiao Li has finished washing, he will inform Xiao Ming to go to dinner together. This is the callback.

2. Callback of Java-medium

However, a careful partner may find that Xiao Li's code is completely written to death, and such an occasion may be suitable for going to dinner with Xiao Ming, but if Xiao Li does not eat after washing and wants to go online with Xiao Wang, this is not applicable. In fact, the above is pseudo code, only to help you understand, in the real case, you need to use the interface to set callbacks. Now let's continue with the example of Xiao Ming and Xiao Li going to dinner to talk about how the interface is used.

Xiao Ming and Xiao Li made an appointment to have breakfast together, but Xiao Li got up a little late and had to wash first. After Xiao Li finished washing, he told Xiao Ming to go to dinner together. Xiaoming is class An and Xiao Li is class B. The difference is that we create a new meal interface EatRice, which has an abstract method eat (). Call the interface in Xiao Ming and implement eat (); Xiao Li declares the interface object and calls the abstract method of the interface. There may be a bit of a twist here, but it doesn't matter, just look at the example.

EatRice interface:

Public interface EatRice {public void eat (String food);} Xiao Ming: public class XiaoMing implements EatRice {/ / Xiao Ming / / Xiao Ming and Xiao Li have dinner together public void eatFood () {XiaoLi xl = new XiaoLi (); / / A calls B's method xl.washFace ("Big Lobster", this) / / this refers to the EatRice interface} @ Override public void eat (String food) {/ / TODO Auto-generated method stub System.out.println ("Xiao Ming and Xiao Li go to eat together" + food);}} Xiao Li: public class XiaoLi {/ / Xiao Li public void washFace (String food,EatRice er) {System.out.println ("Xiao Li wants to wash up") / / B called A's method er.eat (food);}} Test Demo:public class demo {public static void main (String args []) {XiaoMing xm = new XiaoMing (); xm.eatFood ();}}

Test results:

In this way, soft coding is implemented in the form of an interface. Through the form of interface, I can realize that Xiao Li can go to the Internet with Xiao Wang after washing. The code is as follows

Public class XiaoWang implements EatRice {/ / Xiao Wang / / Xiao Wang and Xiao Li go online together public void eatFood () {XiaoLi xl = new XiaoLi (); / A calls B's method xl.washFace ("Dance Flying online", this);} @ Override public void eat (String bar) {/ / TODO Auto-generated method stub System.out.println ("Xiao Wang and Xiao Li go together" + bar);} example 3: Tom

The math teacher asked Tom to do a problem, and instead of staring at Tom while Tom was doing the problem, the math teacher was playing with his mobile phone, waiting for Tom to finish the problem and then tell the teacher the answer.

The math teacher needs a quote from Tom before he can send the question to Tom.

The math teacher needs to provide a method so that Tom can tell him the answer after he has finished the problem.

3 Tom needs a quote from the math teacher so that Tom can give the answer to the teacher instead of the PE teacher next door.

Callback API, which can be understood as teacher interface

/ / callback means that A calls B to do something, and B tells A the result after it is done, during which A can do something else. / / there is a method in this interface, which means the method B uses when telling An after finishing the problem. / / so we must provide this interface so that B can be called back and forth. / / callback API, public interface CallBack {void tellAnswer (int res);}

Math teacher class

/ / the teacher class instantiates the callback API, that is, after the student has finished writing the question, the callback is made through the method provided by the teacher. / / so how do students call the teacher's method? just pass the teacher's reference into the method of the student class. / / and the teacher needs to assign students to answer questions, so it is also necessary to pass in the students' examples. Public class Teacher implements CallBack {private Student student; Teacher (Student student) {this.student = student;} void askProblem (Student student, Teacher teacher) {/ / main method is run by the main thread. In order to implement asynchronous callback, a thread is started to operate on new Thread (new Runnable () {@ Override public void run () {student.resolveProblem (teacher)). }}). Start (); / / after the teacher asks the student to do the problem, while waiting for the student to answer, he can do something else, such as playing with his mobile phone.\ / without having to wait synchronously, this is the advantage of callback. / / of course you can say that it is OK to start a thread for the student to do the problem, but it is impossible for the student to inform the teacher. / / another mechanism is needed to implement the notification process. / / of course, future and callable in multithreading can also achieve the function of data acquisition. For (int I = 1 I < 4 x I + +) {System.out.println ("the teacher played" + I + "second's mobile phone" when students were answering questions);}} @ Override public void tellAnswer (int res) {System.out.println ("the answer is" + res);}}

Student interface

/ / the student's interface. The teacher's reference should be passed into the problem-solving method, otherwise the callback to the specific instance cannot be completed. The advantage of writing as an interface is that many students can implement this interface, and teachers can aggregate students through / / input List when asking questions, which is very convenient. Public interface Student {void resolveProblem (Teacher teacher);}

Student Tom

Public class Tom implements Student {@ Override public void resolveProblem (Teacher teacher) {try {/ / the student got the answer after thinking for 3 seconds and told the teacher through the callback method provided by the teacher. Thread.sleep (3000); System.out.println ("work out"); teacher.tellAnswer (111l);} catch (InterruptedException e) {e.printStackTrace ();}}

Test class

Public class Test {public static void main (String [] args) {/ / Test Student tom = new Tom (); Teacher lee = new Teacher (tom); lee.askProblem (tom, lee) / / result / / wait for the student to answer the question, the teacher plays the mobile phone for 1 second / / wait for the student to answer the question, the teacher plays the mobile phone for 2 seconds / / wait for the student to answer the question, the teacher plays the mobile phone for 3 seconds / / work out// the answer is 111}} "how to implement the callback mechanism in Java" is introduced here. Thank you for your 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