(Translation) understand the callback mechanism in Java, java callback

Source: Internet
Author: User

(Translation) understand the callback mechanism in Java, java callback

Address: http://cleancodedevelopment-qualityseal.blogspot.com/2012/10/understanding-callbacks-with-java.html

Hello, I want to share some things with you today. For example, this is a lot of things used in JavaScript. I want to talk about callback ). You know when to use it. how to use it? Have you really understood its usage in the java environment? When I asked myself these questions, that is why I started to study these questions. The idea behind this is:Control reversal(PS: Wikipedia refers to Inversion of Control (IoC). It is a design principle in Object-Oriented Programming and can be used to reduce the coupling between computer code .) This example describes how the framework works.Hollywood principle: Don't call us. We will call you.("Hollywood principle-Don't call me, we will call you.

The callback mode in Java is simple to understand. The specific example is as follows:

1 interface CallBack {2 void methodToCallBack (); 3} 4 5 class CallBackImpl implements CallBack {6 public void methodToCallBack () {7 System. out. println ("I 've been called back"); 8} 9} 10 11 class Caller {12 13 public void register (CallBack callback) {14 callback. methodToCallBack (); 15} 16 17 public static void main (String [] args) {18 Caller caller = new Caller (); 19 CallBack callBack = new CallBackImpl (); 20 caller. register (callBack); 21} 22}View Code

You may ask me when to use this or ask what is the difference between direct call and callback?

The answer is: Well, this example only shows you how to construct such a callback function in the java environment. Of course it makes no sense to use it in that way. Let's study it more deeply.

The idea in it is to reverse control. Let's use a timer as an example in reality. Suppose you know that there is a special timer that supports the hourly callback function. Specifically, the timer will call the call method you registered every hour.

Example:

We want to update the website time every hour. The following is an example of the UML Model:

Callback interface:

Let's first define the callback interface:

1 import java. util. arrayList; 2 import java. util. list; 3 4 // For example: Let's assume that this interface is offered from your OS to be implemented 5 interface TimeUpdaterCallBack {6 void updateTime (long time ); 7} 8 9 // this is your implementation.10 // for example: You want to update your website time every hour11 class hour implements TimeUpdaterCallBack {12 13 @ Override14 public void updateTime (long time) {15 // print the updated time anywhere in your website's example16 System. out. println (time); 17} 18}View Code

In our example, the system timer supports the callback method:

1 // This is the SystemTimer implemented by your Operating System (OS) 2 // You don't know how this timer was implemented. this example just 3 // show to you how it cocould looks like. how you cocould implement a 4 // callback by yourself if you want. 5 class SystemTimer {6 7 List <TimeUpdaterCallBack> callbacks = new ArrayList <TimeUpdaterCallBack> (); 8 9 public void registerCallBackForUpdatesEveryHour (TimeUpdaterCallBack timerCallBack) {10 callbacks. add (timerCallBack); 11} 12 13 //... this SystemTimer may have more logic here we don't know... 14 15 // At some point of the implementaion of this SystemTimer (you don't know) 16 // this method will be called and every registered timerCallBack17 // will be called. every registered timerCallBack may have a totally18 // different implementation of the method updateTime () and my be19 // used in different ways by different clients.20 public void oneHourHasBeenExprired () {21 22 for (TimeUpdaterCallBack timerCallBack: callbacks) {23 timerCallBack. updateTime (System. currentTimeMillis (); 24} 25} 26}View Code

Finally, we use the web site time Updater in a simple virtual example:

1 // This is our client. it will be used in our WebSite example. it shall update 2 // the website's time every hour. 3 class WebSiteTimeUpdater {4 5 public static void main (String [] args) {6 SystemTimer = new SystemTimer (); 7 TimeUpdaterCallBack webSiteCallBackUpdater = new WebSiteTimeUpdaterCallBack (); 8 SystemTimer. registerCallBackForUpdatesEveryHour (webSiteCallBackUpdater); 9} 10}View Code

 


How to Understand the callback mechanism and template mechanism in java

That is, the callback is reflected in the fact that your classmates call your number. This example is used to compare the callback mechanism in Ajax and the callback + template mechanism used by HibernateTemplate in Spring to make it easier to understand the callback mechanism. Ajax code: Java code functiontest {if (window. activeXObject) {xmlHttp = newActiveXObject (Microsoft. XMLHTTP);} elseif (window. XMLHttpRequest) {xmlHttp = newXMLHttpRequest ();} xmlHttp. onreadystatechange = callback; xmlHttp. open (...); XmlHttp. send (null);} functioncallback {} among them, xmlHttp. onreadystatechange = callback indicates that the callback function is called when the state changes, and this callback is a callback function. Analogy: When xmlHttp sends a request, it is equivalent to when you call your classmates. xmlHttp does not know when the state will change, and you do not know when your classmates will solve the problem. The Callback function is equivalent to your phone number. When the state changes, the callback function is called. After your classmates solve the problem, they will call you to notify you. The callback mechanism and template method of HibernateTemplate in Spring the source code of HibernateTemplaet is very complicated. We can write a simple code to simulate: Java code interfaceCallBack {publicvoiddoCRUD ();} publicclassHibernateTemplate {publicvoidexecute (CallBackaction) {getConnection (); action. doCRUD (); releaseConnection ();} publicvoidadd () {execute (newCallBack () {publicvoiddoCRUD () {System. out. println (execute the add operation ...);}});} publicvoiddelete () {execute (newCallBack () {publicvoiddoCRUD () {System. out. p Rintln (execute the delete operation ...);}});} publicvoidgetConnection () {System. out. println (get connection ...);} publicvoidreleaseConnection () {release connection ...);}} analogy: The execute method can reflect the template mode. Taking the add method as an example, calling the execute method is equivalent to calling your classmates, but your classmates say it takes time, just as the execute method needs to get the connection first, so you pass the CallBack Anonymous class to it, and after it gets connected, it will execute your add operation, which is equivalent to telling your classmates the phone number, he will call you again after solving the problem.

JAVA callback mechanism

Basically, this is a callback mechanism. The interface passed in the method is implemented as an interface of the Listener. when calling the method, the instance of the specific interface implementation can also be passed in advance (usually called registering the Listener ). This situation is common in the event mechanism in Java Swing programming.

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, which is a one-way call that the caller must wait for the execution of the other party to complete;

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, but 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 ).

Asynchronous call implementation is a situation of callback. For example, a method can be returned in advance, and a specific logical execution can be called back and forth by another thread after the execution is completed, notifies the caller.

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.