multithreaded design mode-Java implementation of the future mode

Source: Internet
Author: User

In the previous blog, we introduced the design idea and implementation of the future design pattern, and today we'll talk about how to implement the original package using the JDK.

The built-in future of the JDK is mainly used in the callable interface and the Futuretask class.

Callable are similar to runnable interfaces, classes that implement callable interfaces, and classes that implement runnable, are tasks that can be performed by other threads. The callable interface is defined as follows:

Public interface Callable<v> {
/**
* Computes a result, or throws an exception if unable to does so.
*
* @return Computed result
* @throws Exception If unable to compute a result
*/
V call () throws Exception;
}

The type parameter of the callable is the type of the return value. For example:

Callable<integer> represents an asynchronous computation that eventually returns an Integer object.

The future saves the results of an asynchronous calculation. In practice, you can start a calculation, give the future object to a thread, and then perform other actions. The owner of the future object can obtain it after the result has been calculated. The future interface has the following methods:

 public  interface  future<v>< Span style= "COLOR: #000000" "{ boolean " Cancel ( boolean      mayinterruptifrunning);     boolean   iscancelled ();     boolean   IsDone (); V get ()  throws   Interruptedexception,    Executionexception; V Get ( long  timeout, timeunit unit) throws   Interruptedexception, executionexception, timeoutexception;}  

The call to the first get method is blocked until the calculation is complete. If the call to the second Get method times out before the calculation is complete, a TimeoutException exception is thrown. If the thread running the calculation is interrupted, two methods will throw a interruptedexception. If the calculation is complete, the Get method returns immediately.

If the calculation is still in progress, the Isdone method returns false, or True if it is completed.

You can cancel the calculation by using the Cancel method. If the calculation has not started, it is canceled and no longer starts. If the calculation is running, it is interrupted if the Mayinterrupt parameter is true.

The Futuretask wrapper is a very convenient mechanism to implement both the future and the Runnable interface. The Futuretask has 2 methods of construction:

 PublicFuturetask (callable<v>callable) {        if(Callable = =NULL)            Throw NewNullPointerException ();  This. callable =callable;  This. state = NEW;//ensure visibility of callable    } PublicFuturetask (Runnable Runnable, V result) { This. callable =executors.callable (runnable, result);  This. state = NEW;//ensure visibility of callable}

In general, we will use the callable example to construct a Futuretask object and submit it to the thread pool for processing, and we will show the use of this built-in future pattern.

 Public classRealdataImplementsCallable<string> {    PrivateString param;  Publicrealdata (String param) { This. param =param; } @Override PublicString Call ()throwsException {stringbuffer sb=NewStringBuffer ();  for(inti = 0; i<; i++) {sb.append (param); Try{Thread.Sleep (100); }Catch(Interruptedexception e) {}}returnsb.tostring (); }}

The code above implements the callable interface, its call method constructs the real data we need and returns it, of course, the process is slow, and here we use Thread.Sleep () to simulate it:

 Public classFuturemain { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {//Construction FuturetaskFuturetask<string> Futuretask =NewFuturetask<string> (NewRealdata ("xxx")); Executorservice Executorservice= Executors.newfixedthreadpool (1); //execute futuretask, send request//here the thread is opened for Realdata call () executionExecutorservice.submit (Futuretask); System.out.println ("The request is complete ... "); Try {            //Additional operations can be performed here, where sleep is used instead of other business processesThread.Sleep (200); }Catch(interruptedexception e) {e.printstacktrace (); }        //gets the return value of the call () method//if the call () method does not complete at this point, it will still wait forSYSTEM.OUT.PRINTLN ("Real data:" +futuretask.get ()); }}

The code above is typical of using the future model. When constructing futuretask, use the callable interface to tell Futuretask that the data we need should have a return value. Then we submit the Futuretask to the thread pool, and then we don't have to worry about how the data is generated, we can do other business logic processing, and then call Futuretask.get () to get the actual data when needed.

The future model is often used when dealing with complex business in daily business, and I hope we can master it.

multithreaded design mode-Java implementation of the future mode

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.