Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Using CompletionService in conjunction with ExecutorService batch tasks

Shulou Source: shulou.com Published: 2022-06-01 03:01:54 09月10日 Update

CompletionService is used to submit a set of Callable tasks, and its take method returns the Future object corresponding to a completed Callable task.

If you submit a batch task to Executor and want to get the results after they are completed. To do this, you can save the Future of each task into a collection, and then loop through the collection and call Future's get () to fetch the data. Luckily, CompletionService did it for you.

CompletionService integrates the functions of Executor and BlockingQueue. You can submit the Callable task to it for execution, and then use take and poll methods similar to those in the queue to get the result when it is fully available, like a packaged Future.

The take of CompletionService returns which future is completed first, rather than according to the order in which it is submitted.

Example:

1 import java.util.Random; 2 import java.util.concurrent.Callable; 3 import java.util.concurrent.CompletionService; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.ExecutorCompletionService; 6 import java.util.concurrent.ExecutorService; 7 import java.util.concurrent.Executors; 8 9 public class CallableAndFuture {10 11 public static void main (String [] args) {12 ExecutorService threadPool = Executors. NewFixedThreadPool (10); 13 CompletionService completionService = new ExecutorCompletionService (threadPool); 14 15 for (int I = 0; I < 10; iFix +) {16 final int seq = I Ting 17 System. Out.println ("start submitting" + seq + "task"); 18 completionService.submit (new Callable () {19 20 @ Override21 public Integer call () throws Exception {22 Thread. Sleep (new Random (). NextInt (5000)); 23 return seq;24} 25}); 26} 27 28 for (int I = 0; I < 10) ) {29 try {30 / / take out and remove the Future that represents the next completed task, and wait if no such task currently exists. 31 Integer seq = completionService.take (). Get (); 32 System. Out.println ("1st" + seq + "task return"); 33} catch (InterruptedException e) {34 e.printStackTrace (); 35} catch (ExecutionException e) {36 e.printStackTrace (); 37} 38} 39} 40 41}

Tags: Tasks results methods lucky for this things examples functions objects achievements data queues order loops integration Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft Linux NVidia vpn