Benefits and Use Cases of JDK concurrency toolkit completionservice and executorcompletionservice

Source: Internet
Author: User

Section 6.3.5 completionservice: executor and blockingqueue in Java concurrent programming practices:

"If you submit a group of computing tasks to executor and want to obtain results after the computation is complete, you can retain the future associated with each task and use the get method repeatedly, at the same time, the timeout parameter is specified as 0 to determine whether the task is completed through polling. This method is feasible, but complicated. Fortunately, there is also a better way: to complete the service completionservice. "


What does this mean? We use a complex method and completionservice to complete the process. A clear comparison can help us better understand the original intention of the above paragraph and the completionservice API. In this scenario, five callable tasks return 5 integers respectively. Then, in the main method, we print the returned results in the console according to the task completion sequence.

package net.aty.completeservice;import java.util.concurrent.Callable;import java.util.concurrent.TimeUnit;public class ReturnAfterSleepCallable implements Callable<Integer>{private int sleepSeconds;private int returnValue;public ReturnAfterSleepCallable(int sleepSeconds, int returnValue){this.sleepSeconds = sleepSeconds;this.returnValue = returnValue;}@Overridepublic Integer call() throws Exception{System.out.println("begin to execute.");TimeUnit.SECONDS.sleep(sleepSeconds);System.out.println("end to execute.");return returnValue;}}
This task will accept two parameters. After the specified sleep time, the specified result will be returned. The shorter the sleep time, the more advanced the task is.

1. the tedious method is to use a list to save the future returned by each task, and then poll the future until each future is completed. We do not want to get the result of the first completed task because of the blocking of the previous task. Therefore, we need to set the timeout time to 0 when calling the get method.
Package net. aty. completeservice; import Java. util. arraylist; import Java. util. list; import Java. util. concurrent. executionexception; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. future; import Java. util. concurrent. timeunit; import Java. util. concurrent. timeoutexception; public class traditionaltest {public static void main (string [] ARGs) {int Ta Sksize = 5; executorservice executor = executors. newfixedthreadpool (tasksize); List <future <integer> futurelist = new arraylist <future <integer> (); For (INT I = 1; I <= tasksize; I ++) {int sleep = tasksize-I; // The sleep time int value = I; // The returned result // submit the task future to the thread pool <integer> future = executor. submit (New returnaftersleepcallable (sleep, value); // reserve the futurefuturelist of each task. add (future);} // Round Robin to obtain the returned result of the completed task while (tasks Ize> 0) {for (Future <integer> future: futurelist) {INTEGER result = NULL; try {result = Future. get (0, timeunit. seconds);} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace ();} catch (timeoutexception e) {// timeout exception needs to be ignored, because we set the wait time to 0, as long as the task is not completed, this exception will be reported} // The task has been completed if (result! = NULL) {system. out. println ("result =" + result); // Delete the completed task futurelist from the future list. remove (future); tasksize --; // break is required here; otherwise, a concurrent modification exception is thrown. (You can also declare futurelist as the copyonwritearraylist type) break; // perform the next while loop }}// all tasks have been completed and the thread pool system is closed. out. println ("all over. "); executor. shutdown ();}}
It can be seen that the round-robin future list is very complex, and there are still many exceptions to be handled. timeoutexception exceptions need to be ignored. The dual loop and break are also used to prevent concurrent modification exceptions during the process of traversing the set. So many details need to be considered, it is easy for programmers to make mistakes.

2. Use completionservice
Package net. aty. completeservice; import Java. util. concurrent. completionservice; import Java. util. concurrent. executionexception; import Java. util. concurrent. executorcompletionservice; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; public class completionservicetest {public static void main (string [] ARGs) {int tasksize = 5; executorservice executor = executors. newfixedthreadpool (tasksize); // build completion service completionservice <integer> completionservice = new executorcompletionservice <integer> (Executor); For (INT I = 1; I <= tasksize; I ++) {int sleep = tasksize-I; // The sleep time int value = I; // The returned result // submit the task completionservice to the thread pool. submit (New returnaftersleepcallable (sleep, value) ;}// print the result for (INT I = 0; I <tasksize; I ++) {try {system. out. println (completionservice. take (). get ();} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace () ;}// all tasks have been completed. Disable the thread pool system. out. println ("all over. "); executor. shutdown ();}}
As you can see, completionservice does not have timeoutexeception issues. You do not need to traverse the future list, and do not have to worry about exceptions in concurrent modification.

3. Implementation of completionservice and executorcompletionservice javadoc of completionservice in JDK source code is described as follows:
/** * A service that decouples the production of new asynchronous tasks * from the consumption of the results of completed tasks.  Producers * <tt>submit</tt> tasks for execution. Consumers <tt>take</tt> * completed tasks and process their results in the order they * complete.  */
That is to say, completionservice decouples the tasks submitted by the producer and the results obtained by the consumer. Both the producer and consumer do not need to care about the order in which the tasks are completed, which is guaranteed by completionservice, the consumer must obtain the execution result according to the task completion sequence.
Executorcompletionservice is the implementation of completionservice. It integrates the functions of thread pool executor and blocking queue blockingqueue.
 public ExecutorCompletionService(Executor executor) {        if (executor == null)            throw new NullPointerException();        this.executor = executor;        this.aes = (executor instanceof AbstractExecutorService) ?            (AbstractExecutorService) executor : null;        this.completionQueue = new LinkedBlockingQueue<Future<V>>();    }
It can be inferred that the result is obtained by blocking the queue according to the task completion order. Blocking queues have the following properties: blocking and ordering.
Executorcompletionservice tasks are submitted and executed by the executor. When a task is submitted, the task is first packaged as a queueingfuture
public Future<V> submit(Callable<V> task) {        if (task == null) throw new NullPointerException();        RunnableFuture<V> f = newTaskFor(task);        executor.execute(new QueueingFuture(f));        return f;}

Queueingfuture is a subclass of futuretask. By Rewriting the done method of the futuretask class, you can put the result into blockingqueue when the task is completed.
 /**  * FutureTask extension to enqueue upon completion  */private class QueueingFuture extends FutureTask<Void> {        QueueingFuture(RunnableFuture<V> task) {            super(task, null);            this.task = task;        }        protected void done() { completionQueue.add(task); }        private final Future<V> task;}
Here is a simple description: futuretask. Done (), this method does nothing by default, is a callback, when the task in the submitted thread pool is completed, it will be automatically called. This means that when the task is completed, the queueingfuture. Done () method is automatically executed to add the returned results to the blocking queue. The order of addition is the task completion sequence.
So far, the descriptions of completionservice and executorcompletionservice are complete. Special thanks to the author of http://xw-z1985.iteye.com/blog/1997077. WanqierIt solves the confusion in my reading "Java concurrent programming practices". This article also basically copies the blog post.


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.