Use and confusions of Callable and Future in java

Source: Internet
Author: User

Java also provides a thread pool that can return values, for example:

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 CallableAndFuture {/** * @param args */public static void main(String[] args) {ExecutorService threadPool = Executors.newSingleThreadExecutor();Future<String> future = threadPool.submit(new Callable<String>(){@Overridepublic String call() throws Exception {Thread.sleep(3000);return "future";}});try {System.out.println("waiting...");System.out.println(future.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}}

Wait for a while before the future. get () results come out.

Future. get (300, TimeUnit. MILLISECONDS); however, if this is not completed within the specified time, it stops and runs out of a timeout exception.

Note that the generic and call methods in Callable are of the same type as those in Future.

The following example shows how to return multiple Future objects.

// Create the thread pool ExecutorService pool = Executors. newFixedThreadPool (10); // create a CompletionService instance CompletionService <Integer> completionService = new ExecutorCompletionService <Integer> (pool); // submit a task for (int I = 0; I <10; I ++) {final int index = I; completionService. submit (new Callable <Integer> () {@ Overridepublic Integer call () throws Exception {return index ;}}) ;}// obtain the result for (int I = 0; I <10; I ++) {try {Future <Integer> future2 = completionService. take (); System. out. println (future2.get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace ();}}}

Confused: I don't know where to use it. I have never encountered this situation in business requirements.

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.