Java callback function mechanism

Source: Internet
Author: User

Java callback function mechanism

 

Java callback function mechanism

 

I have referenced some online materials and made some summary below for beginners to learn.

 

I. Overview

 

There are always some interfaces between software modules. In terms of calling methods, they can be divided into three types: Synchronous call, callback, and asynchronous call.

Synchronous call:A blocking call is a one-way call that is returned only after the execution of the other Party completes;

Callback:A two-way call mode, that is, the called party also calls the interface of the other party when the interface is called;

Asynchronous call:A mechanism similar to a message or event solves the synchronization blocking problem. Its call direction is the opposite. When an interface service receives a message or an event, the customer is notified (that is, the customer's interface is called ).

 


Callback and asynchronous call are closely related: callback is used to register asynchronous messages and message notifications are implemented through asynchronous calls.

 

Understanding asynchronous and synchronous

 

 

1. In other words, Asynchronization means that you can continue to execute subsequent actions without waiting for the current action to be completed.

2. Generally, the execution sequence of a program is: from top to bottom. The subsequent actions must be executed only after the previous actions are completed. This is a concept relative to Asynchronization-synchronization.


Case:

A. James called Li Si and asked Li Si to help write the materials.

B. When Li Si received a call, he had his own work to deal with, but he promised Zhang San that after finishing his work, he would help him write the materials and fax them to Zhang San.

C. After the call, Michael will go out for work.

 

Note:

After Mr. Zhang calls Mr. Li and goes out to work, he does not need to wait for Mr. Li to write the materials. Therefore, the messages that James asked Li Si to write materials are asynchronous messages.

On the contrary, if Michael had to wait for Mr. Li to write the materials before he could go out to work, the message would be a synchronous message.

 

Ii. asynchronous implementation

The traditional program executes code one by one from top to bottom. However, this is not the case in many situations in life. In the above cases, if it takes a few hours for Li Si to help James write the materials, then James must wait for several hours, in this way, James may crash or get mad. This kind of one-stop processing is not reasonable.

 

You can use the following methods to solve this problem:

Michael asked Mr. Wang to call Mr. Li. After Mr. Li wrote the materials, Mr. Wang handed over the materials to Mr. Zhang. In this way, James can go out to do other things.

 

The problem was solved reasonably. In the past, the work of Zhang San was completed by Zhang San and Wang Wu. The work was carried out simultaneously on both sides without delay.

 

Iii. Implementation of computer languages

There is a solution. How can we use a program to simulate the implementation?

 

A. For jobs previously handled by A thread, you can add A new thread to achieve asynchronous purposes.

B. Finally, the materials written by Li Si must be handed over to Zhang San for him to use. This is the callback.

 

You can understand the callback as follows:

A sends A message to B,

B. After processing the requirements of A, return the result to,

A then further processes the results returned by B.

 

4. Simulate asynchronous message sending and callback

A,Callback implementation

 

/*** 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 a callback interface.

 

 

B,Message sender

 

/*** Simple Local asynchronous message sending class */public class Local implements CallBack, Runnable {/*** remote message receiving class, simulate point-to-point */private Remote;/*** sent message */private String message; public Local (remote Remote, String message) {super (); this. remote = remote; this. message = message;}/*** send message */public void sendMessage () {/** name of the current thread **/System. out. println (Thread. currentThread (). getName ();/** create a new thread to send messages **/ Thread thread = new Thread (this); thread. start ();/** the current thread continues to execute **/System. out. println (Message has been sent by Local ~!); }/*** Callback function after message sending */public void execute (Object... objects) {/** print the returned message **/System. out. println (objects [0]);/** print the name of the message sending thread **/System. out. println (Thread. currentThread (). getName ();/** Thread that interrupts message sending **/Thread. interrupted ();} public static void main (String [] args) {Local local = new Local (new Remote (), Hello); local. sendMessage () ;}public void run () {remote.exe cuteMessage (message, this );}}

C,Remote message recipient

 

 

/*** Remote class for processing messages **/public class Remote {/*** process messages ** @ param msg receives messages * @ param callBack function processing class */public void executeMessage (String msg, callBack callBack) {/** simulate that the remote class is processing other things and may take a lot of time **/for (int I = 0; I <1000000000; I ++) {}/** after processing other tasks, process the message now **/System. out. println (msg); System. out. println (I hava executed the message by Local);/** execution callback **/callBack.exe cute (new String [] {Nice to meet you ~!}); }}

Execute the main method of the Local class.

Note:

 

Remote.exe cuteMessage (message, this );

The executeMessage method needs to receive a message parameter, indicating the sent message. The CallBack parameter is his own, that is, this here. After a message is sent, the Local class processes the message and calls its own execute method to process the message result.

If this is not used here, but the implementation class of other CallBack interfaces, it cannot be called a "CallBack". In the OO world, it is a "delegate ". That is to say,The "Callback" must be the message sender to process the message result. Otherwise, it cannot be called a callback.This concept must be clear.

 

 

5. More examples of asynchronous + callback programming Modes


1.One day, I called you to ask questions. Of course it was a difficult problem. You couldn't think of a solution at the moment, and I couldn't wait there with a phone, so we agreed:
After the solution is found, call me to notify me. In this way, I will stop the phone and do other things. After XX minutes, my cell phone rang, and you said with high enthusiasm that the problem had been fixed, so you should handle it like this. The story ends here. When you call a mobile phone to tell me that the result is a "Callback" process. My mobile phone number must be told before. This is the registration callback function; my mobile phone number should be valid and the mobile phone can receive your call. This is the callback function that must comply with the interface specifications.


2. A boss was very busy. He didn't have time to stare at the employee's work. Then he told his employee to finish the work and tell him the result.

Create a callback interface so that the boss can tell him how to find the callback: Leave the boss's office address:

 

Package net. easyway. test;/*** this interface is the contact method, regardless of the phone number or contact address, * The boss must implement this interface **/public interface CallBackInterface {public void execute ();}

Create a callback object, that is, the boss himself. Because an employee has to call him after work, the boss must implement the callback interface. Otherwise, Where can the employee contact the boss?

 

 

 

 

Package net. easyway. test;/*** the boss appears as the upper-layer application identity, and the lower-layer application (employee) does not know * which methods are available, so he wants to be used by the lower-layer application (employee) the call must implement this interface **/public class Boss implements CallBackInterface {@ Override public void execute () {System. out. println (received !! + System. currentTimeMillis ());}}

Create a control class, that is, the employee object. He must hold the address of the boss (callback interface). Even if the boss changes after a change, the Office will not change, and he will always find the corresponding boss.

 

 

 

 

Package net. easyway. test;/*** Employee class, which must be remembered. This is an underlying class. The underlying class does not understand upper-layer services. **/public class Employee {private CallBackInterface callBack = null; // inform the boss of the contact information, that is, register public void setCallBack (CallBackInterface callBack) {this. callBack = callBack;} // worker public void doSome () {// 1. started to work. for (int I = 0; I <10; I ++) {System. out. println (the [+ I +] task is finished !); } // 2. Tell the boss that callBack.exe cute ();}}


 

 

Test class:

 

Package net. easyway. test; public class Client {public static void main (String [] args) {Employee emp = new Employee (); // imports the callback object (upper-layer object) and registers the emp. setCallBack (new Boss (); // enable the Controller object to run emp. doSome ();}}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.