Java implementation asynchronous Invocation instance

Source: Internet
Author: User
Tags throwable

In the Java platform, the role of implementing an asynchronous call has the following three roles:

Caller Pickup Voucher Real Data

A caller returns a pickup voucher when it calls a time-consuming operation and cannot return data immediately. And then after a break,
Get real data with the receipt voucher.

So the bridge between the link caller and the real data is the pickup voucher. Let's start by looking at its implementation:

public class futureticket{
Private Object data = null;
Private Boolean completed = false;

Public synchronized void Makerealdata () {
if (this.complited) return;
Gets the time-consuming operation of the data. Use Sleep instead
try{
Thread.Sleep (10000);
}catch (Throwable t) {}
This.data = "Data content returned";
This.completed = true;
Notifyall ();
}

Public synchronized Object GetData () {
while (!this.completed)) {
try{
Wait ();
}catch (Throwable t) {}
}
return this.data;

}
public boolean iscompleted () {
return this.completed;
}
}

To simplify the explanation (not to complicate their relationship), hereObjecTBInstead of real data. and the real implementation
We should put Makedata in a class of real data, and then provide a way to return real data. So for the real
Processing of data and decoupling of receipt vouchers.

For this pickup credential, the caller's invocation is the key to the asynchronous invocation:

PUBLC class requester{
Public Futureticket request () {
Final Futureticket ft = new Futureticket ();

Call a time-consuming operation in a new thread
New Thread () {
public void Run () {
Ft.makerealdata ();
}
}.start ();
return ft;
}
}
After the time-consuming operation is started in a new thread, the bill of lading is returned immediately without waiting for the thread to complete.

The caller can then invoke GetData () to get real data based on ft.iscompleted ().
Of course, the ft.iscompleted () test can be patrolled at specified intervals (very low-level scenarios) or
Wait () when the condition is not met, and then await Makedata's notifyall (); So you're done with a
Asynchronous operations modeled with Java.


Improved:
However, such a call still continues to control the threading operation for the caller. If the caller is a veteran
Programmer, of course, that's fine. But if we entrust the processing of the direct data to the receipt voucher. Call
The operator directly specifies the operation of the data, and then by the receipt of the document to invoke the specified operation, which for the caller is a very
A good relief:

Interface processdata{
public void process (onject data);
}

Public myprocessdata{
public void process (Object data) {
You don't care when the data is first retrieved.
You just have to rule out what to do if you get the data.

System.out.println (data.tostring () + "processing done .....");
INSERT INTO DataBase?
}
}

The pickup voucher knows how to handle the data obtained when the receiving caller requests the data:

public class futureticket{
Private Object data = null;
Private Boolean completed = false;
Private ProcessData PD;

Public Futureticket (ProcessData PD) {
THIS.PD = PD;
}
Public synchronized void Makerealdata (ProcessData PD) {
if (this.complited) return;
Gets the time-consuming operation of the data. Use Sleep instead
try{
Thread.Sleep (10000);
}catch (Throwable t) {}
This.data = "Data content returned";
This.completed = true;
Notifyall ();
}

Public synchronized void PutData () {
while (!this.completed)) {
try{
Wait ();
}catch (Throwable t) {}
}
return this.data;
No return, direct processing.
This.pd.process (This.data);
Alert (?);

}


This method is also not possible.
public boolean iscompleted () {
return this.completed;
}
}

Call:

Final Futureticket ft = new Futureticket (new ProcessData ());

Call a time-consuming operation in a new thread
New Thread () {
public void Run () {
Ft.makerealdata ();
}
}.start ();
Ft.putdata ();

}

In practical programming, the asynchronous processing of the network is often required. such as the client program, if the client program runs before the service program, then the client program needs to automatically connect the service program after the service program starts, and if the service program stops in the client program, it also needs to wait for the service program to run and reconnect without stopping. The following provides a class of methods for asynchronous programming.

The network asynchronous application involves several key points as follows:

Detects if the service app exists after the customer app starts. If it does not exist, wait for the service app to start without clogging up the execution of other tasks that the customer applies. Once the service application is started, the customer application should be in a timely manner to establish a connection.

Customer application and service application in data communication, after the service application exits abnormally, the customer application should be able to detect the exit of the service app. At the same time, the customer application automatically clears the communication link and returns to its initial state, waiting for the service app to restart.

The asynchronous programming of the network involves a timer and timer event first. This timer is used to continuously detect whether customer applications and service applications in the network are connected, and aborts data traffic when the service application is abnormal, returning to the initial state. The network fault can be learned by the exception processing of the network method.

The timer is included in the network communication class, so that the application of this class is not aware of the existence of the timer, and it is convenient to process the network information.

The client program class is structured as follows:

     Public classNetComm implements ActionListener {Javax.swing.Timer Timer=NewJavax.swing.Timer ( the, This);       Socket sock; Privateeventnotifier en;  Public Static intNet_state =0;       InetAddress serveraddr; intServerPort;  PublicNetComm (inetaddress addr,intPort) {serveraddr=addr; ServerPort=Port; } Public voidNetcomm_init () {net_state=1; Try{sock=NewSocket (serveraddr, ServerPort); } Catch(IOException e) {net_state=0;   } timer.start (); } Public voidNetcomm_data () {Try{outputstream OutputStream=Sock.getoutputstream (); BufferedWriter out=NewBufferedWriter (NewOutputStreamWriter (OutputStream));  out. Write ("java by [email protected]");  out. Flush (); BufferedReaderinch=NewBufferedReader (NewInputStreamReader (Sock.getinputstream ())); Boolean more=true;  while(more) {String str=inch. ReadLine (); if(str = =NULL) More =false; Else                 //working with DataSystem. out. println (str); }inch. Close (); } Catch(IOException e) {netcomm_close (); Net_state=0;   } timer.start (); } Public voidNetcomm_close () {if(Sock! =NULL)Try{sock.close (); } Catch(IOException e) {}} Public voidactionperformed (ActionEvent e) {if(Net_state = =0) Netcomm_init (); ElseNetcomm_data (); }            

In the above program, you can also provide a callback function for an external application to notify the application when a network exception or recovery is normal. The network communication classes for service applications are similar and can be placed in the same class.

Java implementation asynchronous Invocation instance

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.