ExecutorCompletionService in Java

By Arvind Rai, November 15, 2023
Java ExecutorCompletionService is the implementaion of CompletionService interface. It has take() that returns only those those threads which has completed its task. The Callable threads submitted to ExecutorCompletionService, can be obtained using take() method after their task completion.

Example

package com.concretepage;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;

public class ExecutorCompletionServiceTest {
	public static void main(String... args) throws InterruptedException, ExecutionException{
		Executor ex= Executors.newCachedThreadPool();
		CompletionService<Long> cs = new ExecutorCompletionService<Long>(ex);
		cs.submit(new Worker());
		cs.submit(new Worker());
		cs.submit(new Worker());
		for(int i=0;i<3;i++){
			long l=cs.take().get();
			//utilize the result 
			System.out.println(l);
		}
	}

}
 class Worker implements Callable{

	@Override
	public Long call() throws Exception {
		//do some task and return back
		return System.currentTimeMillis();
	}
	 
 }
There is a thread named as worker which returns some value. We have added three tasks by three threads in executor. All threads will process the result and will return the value in ExecutorCompletionService object. The role of ExecutorCompletionService is that when we try to get retuned value of thread, ExecutorCompletionService will return the value only of those threads which has completed its task.
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us