Future/futuretask and callable of Java multithreaded programming

Source: Internet
Author: User

There is a scenario in which sending data to a server with multithreading requires knowing that each thread is sent successfully, and all threads are sent to finish before the next round of calculations and sends. If you use traditional multithreading, you need to start multiple threads, and then send the data separately in each thread, externally waiting for each thread to be sent out in some way, and then the subsequent computations. The code for this implementation is bloated, providing a callable+future method in Java that makes asynchronous multithreaded calls synchronous.


Callable

In multithreaded programming in Java, there are thread and runnable two ways to create a new thread, where runnable encapsulates a task that runs asynchronously and can be thought of as an asynchronous method without any parameters and return values. The callable interface is similar to runnable, and both are designed for classes whose instances might be executed by another thread, except that:


Runnable does not return a result and cannot throw a checked exception. The callable has a return result and can throw an exception.

Runnable defines the Run method, and callable defines a method called call without any parameters.

In addition, the type parameter of the callable interface is also the type of the return value.


Public interface Callable {

/**

* 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;

}

Future

The future represents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation. You can only use the Get method to get the results after the calculation is complete and, if necessary, block this method before the calculation is complete. Cancellation is performed by the Cancel method. Other methods are provided to determine whether the task is completed properly or canceled. Once the calculation is complete, you can no longer cancel the calculation. If you use the future for the sake of cancellation and do not provide the available results, you can declare the Future<?> form type and return null as the result of the underlying task.


When using the future object, you can start a calculation, give the calculation to a thread, and then do your own thing. The owner of the future object can get it after the result has been calculated.


Public interface The future {

Boolean Cancel (Boolean mayinterruptifrunning);

Boolean iscancelled ();

Boolean IsDone ();

V get () throws Interruptedexception, executionexception;

V get (long timeout, timeunit unit) throws Interruptedexception, Executionexception, timeoutexception;

}

Futuretask

The Futuretask wrapper is a convenient mechanism for converting callable to future and runnable, which simultaneously implements both interfaces. For example:


Callable Comput = ...;

Futuretask task = new Futuretask (comput);

Thread t = new thread (Task); It ' s a Runnable

T.start ();

...

Integer result = T.get (); It ' s a future

So you can use Futuretask to wrap callable or runnable objects. Because Futuretask implements the runnable, the executor class that futuretask submits to the thread pool is executor executed.


Examples of using Future+callable+executorservice


Import java.util.ArrayList;

Import java.util.List;

Import java.util.concurrent.Callable;

Import java.util.concurrent.ExecutionException;

Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors;

Import Java.util.concurrent.Future;

public class Futuretest {

public static class Task implements callable {

Private long ID;

Public Task (long ID) {

This.id = ID;

}

@Override

Public String Call () throws Exception {

System.out.printf ("Thread#%s:in call\n", this.id);

return this.id + "";

}

}

public static void Main (string[] args) throws Interruptedexception, Executionexception {

List results = new ArrayList ();

Executorservice Execservice = Executors.newcachedthreadpool ();

for (int i=0; i<10;i++)

Results.add (Execservice.submit (New Task (i)));

For (the future Res:results)

System.out.println (Res.get ());

}

}

As you can see, using the future+callable mode is useful for scenarios where you need to wait for multiple threads to execute the result, which is used in the batch operation of HBase.


Future/futuretask and callable of Java multithreaded programming

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.