Detailed description of Future mode in Java multi-thread programming

Source: Internet
Author: User

Detailed description of Future mode in Java multi-thread programming

In Java multi-thread programming, the commonly used multi-thread design modes include: Future mode, Master-Worker mode, Guarded Suspeionsion mode, unchanged mode, and producer-consumer mode. This article focuses on the Future model. The addresses for other multi-threaded design models are as follows:
The addresses for other multithreading design modes are as follows:
Details about the Master-Worker mode: details about the Master-Worker mode in Java multi-thread programming
Details about the Guarded Suspeionsion mode: details about the Guarded Suspeionsion mode in Java multi-thread programming
Explanation of the unchanged mode: Explanation of the unchanged mode in Java multi-thread programming
Explanation of producer-consumer mode: Explanation of producer-consumer mode in Java


1. Core Ideas of the Future model

The core of the Future model is to remove the wait time of the main function and enable the original waiting period to be used to process other business logic (according to Java program performance optimization).

The Future model is similar to a product order. During online shopping, after submitting the order, you do not have to wait at home for the time of receipt. you can do other things first. In programming, when a request is submitted and a response is expected, the response may be slow. Traditionally, you have to wait until the reply is received and then do other things. However, if you use the Future design model, you do not have to wait for the answer to come. You can do other things while waiting for the answer.

For example, the following request call process sequence diagram. It takes a long time for a call request to be returned. The graph on the Left needs to wait until data is returned before other operations can continue. In the diagram on the right, the client does not have to wait until other tasks can be done. The server segment immediately returns the result to the client after receiving the request. The result is not a real result (Virtual result), that is, a false data is obtained first, and other operations are performed.


2. Future mode Java Implementation

Client implementation

The main functions of the Client include: 1. Return a FutureData; 2. Enable a thread to construct RealData.

Public class Client {public Data request (final String string) {final FutureData futureData = new FutureData (); new Thread (new Runnable () {@ Overridepublic void run () {// The construction of RealData is slow, so it is placed in a separate thread to run RealData realData = new RealData (string); futureData. setRealData (realData );}}). start (); return futureData; // directly return FutureData }}
Data Implementation

Both FutureData and RealData implement this interface.

public interface Data {String getResult() throws InterruptedException;}
FutureData implementation

FutureData is the key to the Future model. It is actually the proxy of real data RealData, which encapsulates the waiting process for obtaining RealData.

// FutureData is the key of the Future mode. It is actually the proxy of real Data RealData and encapsulates the waiting process for obtaining RealData public class FutureData implements Data {RealData realData = null; // FutureData is the encapsulation of RealData boolean isReady = false; // whether public synchronized void setRealData (RealData realData) {if (isReady) return; this. realData = realData; isReady = true; notifyAll (); // RealData has been injected into FutureData and the getResult () method is notified.} @ Overridepublic synchronized String get Result () throws InterruptedException {if (! IsReady) {wait (); // wait until RealData is injected into FutureData} return realData. getResult ();}}
RealData implementation

RealData is the final data to be used, and its constructor is slow.

Public class RealData implements Data {protected String data; public RealData (String data) {// use the sleep method to indicate that the RealData construction process is very slow. try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} this. data = data ;}@ Overridepublic String getResult () {return data ;}}
Test Run

The main function is mainly responsible for calling the Client to initiate a request and use the returned data.

Public class Application {public static void main (String [] args) throws InterruptedException {Client client = new Client (); // return immediately because FutureData is obtained, instead of RealDataData data = client. request ("name"); // here you can use a sleep to replace processing of other business logic // in the Process of processing these business logic, RealData is also being created, this makes full use of the waiting time Thread. sleep (2000); // use the real data System. out. println ("data =" + data. getResult ());}}

3. Embedded JDK implementation in Future mode

Because Future is a very common multi-threaded design mode, it is embedded with the implementation of the Future mode in JDK. These classes are included in the java. util. concurrent package. Among them, the most important is the FutureTask class, which implements the Runnable interface and runs as a separate thread. In its run () method, call the Callable interface through the internal Sync class, and maintain the returned objects of the Callable interface. When the FutureTask. get () method is used, the Callable interface will return the returned object. Similarly, for the above instances, if you use the built-in JDK implementation, you need to make the following adjustments.

First, the Data interface and FutureData are not needed. JDK helps us implement it.

Second, change RealData to the following:

Import java. util. concurrent. Callable; public class RealData implements Callable
 
  
{Protected String data; public RealData (String data) {this. data = data ;}@ Overridepublic String call () throws Exception {// use the sleep method to indicate that the real business is very slow. try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} return data ;}}
 
Finally, the following code is called during the test:

Import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. futureTask; public class Application {public static void main (String [] args) throws Exception {FutureTask
 
  
FutureTask = new FutureTask
  
   
(New RealData ("name"); ExecutorService executor = Executors. newFixedThreadPool (1); // use the thread pool // execute FutureTask, which is equivalent to the client in the previous example. request ("name") sends the executor request. submit (futureTask); // here you can use a sleep to replace processing of other business logic. // in the Process of processing these business logic, RealData is also being created, this makes full use of the waiting time Thread. sleep (2000); // use real data // if the call () is not completed, it will still wait for System. out. println ("Data =" + futureTask. get ());}}
  
 

This article is complete. Indicate the source for reprinting.

References
GE yiming, Java program performance optimization. Tsinghua University Press.



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.