Turn multithreaded design mode-Java native implementation of the future mode

Source: Internet
Author: User
Tags visibility stringbuffer

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> {    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:

Public Futuretask (callable<v> callable) {        if (callable = = null)            throw new NullPointerException ();        this.callable = callable;        This.state = NEW;       Ensure visibility of callable    }public Futuretask (Runnable Runnable, V result) {    this.callable = Executors.call Able (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 class Realdata implements callable<string> {    private String param;    Public realdata (String param) {        this.param = param;    }    @Override public    String call () throws Exception {        StringBuffer sb = new StringBuffer ();        for (int i = 0; i<; i++) {            sb.append (param);            try {                thread.sleep (+);            } catch (Interruptedexception e) {                            }        }        return sb.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 class Futuremain {public    static void Main (string[] args)            throws Executionexception, interruptedexception {        //construction futuretask        futuretask<string> futuretask = new Futuretask<string> ( New Realdata ("xxx"));        Executorservice Executorservice = Executors.newfixedthreadpool (1);        Execute futuretask, send request        //Open thread here to Realdata call () execution        executorservice.submit (futuretask);        SYSTEM.OUT.PRINTLN ("Request complete ... ");        try {            //can perform other additional operations here, using sleep instead of other business processing            thread.sleep ();        } catch (Interruptedexception e) {            e.printstacktrace ();        }        Gets the return value of the call () method        //If the call () method does not complete at this time, it will still wait for        System.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.

Turn multithreaded design mode-Java native 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.