14. Future mode in Java, 14. JavaFuture Mode

Source: Internet
Author: User

14. Future mode in Java, 14. JavaFuture Mode

Jdk1.7.0 _ 79

This article is actually a continuation or supplement to the submit method of the above 13. ThreadPoolExecutor thread pool. In the submit method mentioned above, FutureTask appears, which has to stop and redirect to Java's Future mode.

Future is A design mode in concurrent programming. For multithreading, thread A needs to wait for the result of thread B. It does not need to wait until thread B. You can get A Future first, after B has the result, obtain the actual result.

ExecutorService executor = Executors. newSingleThreadExecutor (); Future <String> future = executor. submit (callable); // The Result of the main thread needing the callable thread. Obtain a future FutureSystem first. out. println (future. get (); // obtain the actual result based on the get method after the result is obtained. Of course, if the callable thread does not execute the get method, it will block the execution, if the execution is complete, the result is directly returned or an exception is thrown.

That is to say, Future represents the result of an asynchronous calculation.

The above shows the running principle of the Future mode. Based on the online example, we can implement a Future mode on our own.

1 package com. future; 2 3/** 4 * Data result 5 * Created by yulinfeng on 6/18/17.6 */7 public interface Data {8 String getResult () throws InterruptedException; 9}
1 package com. future; 2 3/** 4 * actual calculation process of results 5 * Created by yulinfeng on 6/18/17. 6 */7 public class RealData implements Data {8 protected String data; 9 10 public RealData (String data) {11 try {12 System. out. println ("computing result"); 13 Thread. sleep (3000); // 14} catch (InterruptedException e) {15 e. printStackTrace (); 16} 17 this. data = data + "world"; 18} 19 20 public String getResult () throws InterruptedException {21 return data; 22} 23}
1 package com. future; 2 3/** 4 * real result RealData proxy 5 * Created by yulinfeng on 6/18/17. 6 */7 public class FutureData implements Data {8 RealData realData = null; // encapsulation of RealData, proxy RealData 9 boolean isReady = false; // are you sure you have prepared 10 11 public synchronized void setResultData (RealData realData) {12 if (isReady) {13 return; 14} 15 this. realData = realData; 16 isReady = true; 17 notifyAll (); // realData already exists Injected to futureData, notifying getResult Method 18} 19 20 public synchronized String getResult () throws InterruptedException {21 if (! IsReady) {22 wait (); // The data has not been computed, blocking wait 23} 24 return realData. getResult (); 25} 26}
1 package com. future; 2 3/** 4 * The main functions of the Client include: 1. returns a FutureData; 2. start a thread to construct RealData 5 * Created by yulinfeng on 6/18/17. 6 */7 public class Client {8 9 public Data request (final String string) {10 final FutureData futureData = new FutureData (); 11 12/* the calculation process is slow, put it in one Thread separately */13 new Thread (new Runnable () {14 15 public void run () {16 RealData realData = new RealData (string); 17 futureData. setResultData (realData); 18} 19 }). start (); 20 21 return futureData; // first return a "false" futureData22} 23}
1/*** calls the Client to initiate a request and use the returned data. 3 * Created by yulinfeng on 6/18/17. 4 */5 public class Main {6 public static void main (String [] args) throws InterruptedException {7 Client client = new Client (); 8 System. out. println ("Prepare calculation result"); 9 Data data = client. request ("hello"); // immediately returns a "false" futureData. You can run other tasks 10 System instead of waiting for data to be returned. out. println ("execute other tasks"); 11 Thread. sleep (3000); // simulate other tasks 12 System. out. println ("data calculation result:" + data. getResult (); 13} 14}

After carefully reading the above procedures, it is not difficult to find that the Future mode isAsynchronous request and proxy Modes. Of course, the Future model has been implemented for us in JDK.

Modify the RealData class:

1 package com. future; 2 3 import java. util. concurrent. callable; 4 5/** 6 * actual calculation process of the result 7 * Created by yulinfeng on 6/18/17. 8 */9 public class RealData2 implements Callable <String> {10 protected String data; 11 12 public RealData2 (String data) {13 this. data = data; 14} 15 public String call () throws Exception {16 try {17 System. out. println ("computing result"); 18 Thread. sleep (2000); // Simulated Calculation Result 19} catch (InterruptedException e) {20 e. printStackTrace (); 21} 22 this. data = data + "world"; 23 return data; 24} 25}

Modify the Main test class:

1 package com. future; 2 3 import java. util. concurrent. executionException; 4 import java. util. concurrent. executorService; 5 import java. util. concurrent. executors; 6 import java. util. concurrent. future; 7 8/** 9 * is responsible for calling the submit of Executor and using the returned data. 10 * Created by yulinfeng on 6/18/17.11 */12 public class Main2 {13 14 public static void main (String [] args) throws InterruptedException, ExecutionException {15 ExecutorService client = Executors. newSingleThreadExecutor (); // similar to Client16 System. out. println ("Prepare calculation result"); 17 Future <String> data = client. submit (new RealData2 ("hello"); // similar to Client. request18 System. out. println ("execute other tasks"); 19 Thread. sleep (3000); 20 System. out. println ("data calculation result:" + data. get (); 21} 22}

Now, go back to the solution that has not been completed before using the actexecutorservice # submit method.

Similar to the Client # request method above, you can create a FutureData instance first in Client # request, while a FutureTask instance is created in AbstractExecutorService # submit, then the Client # request creates a new thread for asynchronous task execution and returns FutureData directly. In the same way, the task is also handed over to the execute method in AbstractExecutorService # submit, and the FutureTask is directly returned. Of course, the Future mode implementation in JDK is more complicated.

In the 12. ThreadPoolExecutor thread pool Principle and Its execute method, we explain the execute method. In the ThreadPoolExecutor $ Worker # runWorker method, row 1,145th calls the task:

//ThreadPoolExecutor$Worker#runWorkertask.run();

Submit calls execute to execute the run method. The actual execution is the run method in FutureTask. In FutureTask # run, you can see asynchronous execution of Callable tasks and save the results.

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.