Difference between ExecutorService and CompletionService in Java

Source: Internet
Author: User

Currently, multithreading in Java usually does not directly use the Thread object, but uses the ExecutorService class under java. util. concurrent to initialize a Thread pool for our use.

Previously, I used to maintain a list to save the Future object returned by the callable task of the submit.

Traverse the list in the main thread and call the get () method of Ure to obtain the return value of the Task.

 

However, in many places, I will see some code wrap ExecutorService through CompletionService, and then call its take () method to retrieve the Future object. I have never studied the differences between the two.

After reading the source code today, I will understand it.

 

The main difference between the two is that the submit tasks are not necessarily completed by adding them to the list maintained by themselves.

Every Future object traversed from the list is not necessarily in the finished state. Calling the get () method will be blocked, if the system is designed to continue subsequent tasks based on the results after each thread is completed, an additional wait time will be added for the threads that are completed after the list.

 

CompletionService maintains a BlockingQueue that stores the Future object. Only when the state of the Future object ends will it be added to this Queue. The take () method is actually the Consumer in the Producer-Consumer. It will retrieve the Future object from the Queue. If the Queue is empty, it will block it until a completed Future object is added to the Queue.

Therefore, the first task must be taken out first. This reduces the unnecessary waiting time.

Related Article

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.