Java callback function mechanism
Reference to some of the online information, the following also made some summary for beginners to learn.
I. Overview
There is always a certain interface between software modules, which can be divided into three categories: synchronous Invocation, callback, asynchronous invocation .
Synchronous invocation: a kind of blocking call, the caller waits for the other party to complete before returning, it is a one-way invocation;
callback: a two-way invocation pattern, that is, the callee will also invoke the interface when the interface is called;
Asynchronous invocation: a mechanism similar to a message or event that solves the problem of synchronous blocking , which is called in the opposite direction, and the service of the interface proactively notifies the client (that is, the interface that invokes the client) when a message is received or an event occurs .
the relationship between callbacks and asynchronous calls is very tight: use callbacks to implement the registration of asynchronous messages, and to implement notification of messages through asynchronous calls.
Understanding Asynchronous and synchronous
1. It is common to say that async does not need to wait for the current execution to complete, so you can continue to perform the subsequent actions.
2. Usually the order in which a program executes is: From top to bottom, execution in turn. The subsequent action must wait for the previous action to complete before executing. This is a concept that is relative to asynchrony-synchronous.
Case:
A, Zhang San call John Doe, let John Doe help write a material.
B, John Doe received the phone when the hand has his own work to deal with, but he promised Zhang San, busy hand after work immediately help Zhang San write good material, and fax to Zhang San.
C, after the phone, Zhang San out of office.
Description
Zhang San to Lee four through the telephone, went out to work, he does not need to wait for John Doe to write the material well before going out. Then the message that Zhang San let John Doe write material belongs to the asynchronous message.
On the contrary, if the Zhang San must wait for John Doe to write the material in order to go out to work, then this message belongs to the synchronization message.
Second, the realization of asynchronous
Traditional program execution code is executed from top to bottom, one at a line. But there are many things in life is not so, in the above case, if John Doe need a few hours later to help Zhang San write good material, the three must wait a few hours, so Zhang San may collapse or crazy. Such a dragon-like treatment, the display is not very reasonable.
You can use the following methods to handle this problem:
Zhang San find Harry to John Doe call, wait for Li four write good material, from Harry to Zhang San. So Zhang San can go out and do other things.
The problem has been resolved reasonably, before Zhang 31 line of work, by Zhang San and Wang 52 line to complete, both sides at the same time, do not delay each other.
Third, the realization of computer language
How to use the program to simulate the implementation?
A, work that was previously handled by a thread can be asynchronous by adding a new thread.
B, the last John Doe written material must be handed to Zhang San, to do his use. This is the callback.
Callback you can understand this:
A send a message to B,
b After handling a required thing, return the result to a,
A further treatment of the results of B return.
Iv. sending and callback of analog asynchronous messages
A, the implementation of the callback
/** * Callback interface */public interface CallBack { /** * Execute callback method * @param objects Returns the processed result as a parameter to the callback method * /public void execute (Object ... objects); }
Java is an object-oriented language, so the callback function becomes the callback interface.
B, the sender of the message
/** * Simple local send Asynchronous Message class */public class Local implements callback,runnable{/** * Remote Receive Message class, simulation point-to-point */private remote remote; /** * Message sent out */private String message; Public Local (remote remote, String message) {super (); This.remote = remote; this.message = message; }/** * Send message */public void SendMessage () {/** The name of the current thread **/System.out.println ( Thread.CurrentThread (). GetName ()); /** creates a new thread to send the message **/thread thread = new thread (this); Thread.Start (); /** The current thread continues execution of **/System.out.println ("Message has been sent by local~!"); /** * Callback function after sending message */public void execute (Object ... objects) {/** print returned message **/Syst Em.out.println (Objects[0]); /** prints the thread name of the sending message **/System.out.println (Thread.CurrentThread (). GetName ()); /** interrupts the thread **/sending the message thread.intErrupted (); } public static void Main (string[] args) {Local local = new local (new Remote (), "Hello"); Local.sendmessage (); public void Run () {remote.executemessage (message, this); } }
C,Recipients of remote messages
/** * * * */public class remote { /** * Processing message * @param msg received message * @param CallBack callback function processing class * /public void ExecuteMessage (String msg,callback callBack) { /** It may take a lot of time for the analog remote class to process other things, **/for (int i=0;i<1000000000;i++) { } /** to handle the other things, and now to process the messages **/ System.out.println (msg); System.out.println ("I Hava executed the message by Local"); /** execution Callback **/ callback.execute (new string[]{"Nice to meet you~!"}); }
executes the main method of the Local class.
Note in the local class:
Remote.executemessage (message, this);
The executemessage method needs to receive a message parameter, which means that the messages are sent out, while the callback parameter is himself, that is, this. Indicates that the message is sent, handled by the local class itself, and calls its own Execute method to process the message result.
If this is not used here, but with other implementations of the callback interface, then it can not be called "callback", in the OO world, it belongs to "delegation". In other words,"callback" must be the sender of the message to process the message result, otherwise it cannot be called a callback. The concept must be clear.
V. More examples of asynchronous + callback programming patterns
1. One day, I call to ask you questions, of course, is a problem, you can not think of a solution, I can't hold the phone there silly wait, so we agreed: so you want to
out of the way after the phone call me, so I hung up the phone to do other things. After xx minutes, my cell phone rang, you cheerfully said that the problem has been done, should be so handled. The story ends here. One of them, you later called the phone to tell me the result is a "callback" process ; my mobile phone number must be told you before, this is the registration callback function , my mobile phone number should be valid and the phone can receive your call , This is the callback function that must conform to the interface Specification .
2. One of the bosses was very busy, he had no time to stare at the staff, and then he told his employees to finish the current events and tell him the result of the work.
Create a callback interface that tells the boss how to find his way through the job: Leave the boss's office address:
Package net.easyway.test; /** * This interface is the way to contact, whether it is a phone number or contact address, as a * boss must implement this interface * */public interface Callbackinterface { public void execute (); }
create callback object, is the boss himself, because the staff to call him after the work, so the boss must implement callback interface, or where employees go to find the Boss?
Package net.easyway.test; /** * The boss is a top-level application, the lower-level application (employees) is not aware of the method, so he wants to be a downlevel application (employee) Call must implement this interface * */public class Boss Implements Callbackinterface { @Override public Void execute () { System.out.println ("Received!! "+ System.currenttimemillis ()); } }
Create the control class, which is the employee object, he must hold the boss's address (callback interface), even if the boss changed stubble and stubble, the office is unchanged, always find the corresponding boss.
Package net.easyway.test; /** * Employee class, it must be remembered that this is an underlying class, the underlying is not aware of the upper service * * */Public class Employee { private callbackinterface CallBack = null; Tell the boss the contact way, that is, register public void Setcallback (Callbackinterface callBack) { this.callback = callBack; } Workers work public void Dosome () { //1. Started working for (int i=0;i<10;i++) {System.out.println ("" " + i +" " It's done! "); } 2. Tell the boss to finish Callback.execute (); } }
Test class:
Package net.easyway.test; public class Client {public static void Main (string[] args) { employee emp = new Employee (); The callback object (upper object) is passed in and registered Emp.setcallback (new Boss ()); Open the Controller object to run emp.dosome ();} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java callback function mechanism