Understanding and implementation of Java callback function

Source: Internet
Author: User
Tags sendmsg

A callback function, or callback, refers to a piece of executable code that passes through a function parameter to another code. This design allows the underlying code to invoke subroutines defined at the top level.

In Java, we use interfaces to implement callbacks. As an example,

The so-called callback is that programmer a wrote a program (program a), which reserved a callback function interface, and encapsulated the program. Programmer B wants A to invoke a method in its own program B, so he callbacks his method in B through the interface in a.

As an example:

1. First define a class caller, according to the above definition is programmer a written by program A, this class to save an interface reference.

 Public class Caller {    private  mycallinterface callinterface;          Public Caller () {    }        publicvoid  setcallfunc (mycallinterface callinterface) {         this. callinterface = callinterface;    }          Public void Call () {        callinterface.printname ();    }}

2. The definition of the interface makes it easy for programmer B to implement the interface according to the definition programming.

 Public Interface Mycallinterface {    publicvoid  printname ();}

3. The third is the definition of programmer b written by program B

 Public class Implements mycallinterface {     @Override    publicvoid  printname () {        System.out.println ("This is the client Printname method");}    }

4. Testing

 Public class Test {    publicstaticvoid  main (string[] args) {        new Caller ();        Caller.setcallfunc (new  Client ());        Caller.call ();    }}

In this way, we can see that the interface member variable is reserved in program a so that program a can invoke this interface variable to implement the method of the class arbitrarily. And the method that program B is called is the callback function.

The next step is to look at a specific implementation:

The following is a tool class that uses the Java callback function to implement a test function run time:

If we were to test the execution time of a method of a class, we would typically do this:

 Public   classTestobject {/*** A method to be tested for a more time-consuming cycle*/        Public   Static   voidTestMethod () { for(inti= 0; i< 100000000; i++){                        }      }      /*** A simple way to test the execution time of a method*/        Public   voidTesttime () {LongBegin = System.currenttimemillis ();//Test Start TimeTestMethod ();//test Method        LongEnd = System.currenttimemillis ();//Test End TimeSystem.out.println ("[Use time]:" + (End-begin));//Print usage Time    }             Public   Static   voidMain (string[] args) {testobject test=NewTestobject ();      Test.testtime (); }  }

Let's do a function that implements the same functionality but is more flexible:

First, set a callback interface:

 Public   Interface   CallBack {      // method   of executing callback operation    void  execute () ;  }  

Then write a tool class:

 Public   classTools {/*** Test function usage time by defining the Execute method of the callback interface *@paramCallBack*/        Public   voidtesttime (CallBack CallBack) {LongBegin = System.currenttimemillis ();//Test Start TimeCallback.execute ();///Perform callback operations        LongEnd = System.currenttimemillis ();//Test End TimeSystem.out.println ("[Use time]:" + (End-begin));//Print usage Time    }             Public   Static   voidMain (string[] args) {Tools tool=NewTools (); Tool.testtime (NewCallBack () {//defining the Execute method             Public   voidExecute () {//Here you can add one or more methods to test the run-timeTestobject.testmethod ();      }          }); }  }

A more time-consuming method to test:

 Public   class   testobject {      /**       * A method to be tested for a more time-consuming cycle               */ public   static   void  testMethod () {           for int  i= 0; i< 100000000; i++) {                        }       }}

Here we do not write program B to implement the callback interface, but by anonymous inner class method to implement. The callback function is also implemented.

Then let's see why we want to use the callback function:

The so-called callback function is a called b,b at the appropriate time and back to call a. Most of the time because it is a single thread, a does not have to wait for B to call it, because a can invoke the action it needs after B. So callbacks are seen in the event-driven mechanism. Because a does not know when B will complete after the call is finished, a does not know when B will complete. And the only know B when the completion of course is B himself, so when B is completed by a callback function to notify A, oneself has completed, at this time a just know to do the following operation. If this is not the case, a can only continue to ask whether B has been completed (that is, polling), visible is very low efficiency, the implementation is also very troublesome.

Callbacks usually occur when there are two different threads that need to be synchronized, but there are times when it is not necessary to use semaphores for real thread synchronization because it can be complex and unnecessary. So there's a callback. As for the callback to do, of course, it is your own decision.

Talk about synchronous callbacks and asynchronous callbacks:

Synchronization refers to the invocation of a method, the caller waits for the method to perform a complete execution of the task, and then control back to the caller, asynchronous refers to the invocation of a method, the caller does not wait for the method to perform the completion of the task is returned, when the completion of the task will automatically execute the caller incoming code.

Synchronous:
void RunTask {  doTask1 ()  doTask2 ()}

Synchronous call, executing doTask1 in execution doTask2

Asynchronous
DoTask1 (new  Callback () {  void call () {    doTask3 ()  }});d OTask2 ();

Asynchronous callbacks, which execute DoTask1 and doTask2 at the same time, and execute after DoTask1 execution doTask3

At the same pace with a time-consuming task, an asynchronous callback is appropriate for a time-consuming task, and the task called after it is called does not matter.

Look at a case of an asynchronous callback:

Callback Interface class:

/***/Publicinterface  cscallback    {public void process (String status);}

Impersonate the client:

/*** Callback Mode-impersonate the client class*/ Public classClientImplementsCscallback {PrivateServer server;  PublicClient (server server) { This. Server =server; }     Public voidSendmsg (FinalString msg) {System.out.println ("Client: The message sent is:" +msg); NewThread (NewRunnable () {@Override Public voidrun () {server.getclientmsg (Client). This, MSG);        }}). Start (); System.out.println ("Client: Asynchronous Send succeeded"); } @Override Public voidprocess (String status) {System.out.println (Client: Service-side callback status: "+status); }}

Analog Service side:

/*** Callback mode-Analog service-side class*/ Public classServer { Public voidgetclientmsg (cscallback cscallback, String msg) {System.out.println ("Server side: The server received a message sent by the client:" +msg); //the analog service side needs to data processing        Try{Thread.Sleep (5 * 1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Server: Data processing succeeded, return to success status 200"); String Status= "200";    Cscallback.process (status); }}

Test class:

/***/Publicclass  callbacktest    {publicstatic  void  main (string[] args) {        new  Server ();         New Client (server);        Client.sendmsg ("server,hello~");}    }

Understanding and implementation of Java callback function

Related Article

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.