Java. util. Concurrent. completionservice usage

Source: Internet
Author: User
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10,TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000));

1. Use a list to save the future object returned by the callable task of threadpoolexecutor submit:

List<Future<Object>> futureList...threadPool.submit(new Callable(){...})

Traverse the list in the main thread and call the get () method of ure to obtain the return value of the task:

for (Future<Object> future : futureList) {       future.get();}

Because submit tasks are not necessarily completed by adding them to the list maintained by themselves, each future object traversed from the list is not necessarily in the completed State. At this time, get () is called () the method will be blocked, so that the threads that are behind the list but completed first will increase the additional waiting time.

Therefore, if you use list to save the future object, it is not necessarily taken out first.

2. Package threadpoolexecutor through completionservice, and then call its take () method to get the future object.

CompletionService<Object> completionService = new ExecutorCompletionService<Object>(threadPoolExecutor);completionService.submit(new Callable(){...});for(;;){   Future<Object> future=completionService.take();}

Completionservice maintains a blockingqueue that stores the future object. The future object will be added to this queue only when the State of the future object ends. The take () method will retrieve the future object from the queue. If the queue is empty, it will be blocked until a completed future object is added to the queue.
Therefore, when using completionservice, the first completed task must be taken out first, which reduces the unnecessary waiting time.

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.