Skip to content

Instantly share code, notes, and snippets.

@dopoljak
Last active December 31, 2015 16:18
Show Gist options
  • Save dopoljak/8012299 to your computer and use it in GitHub Desktop.
Save dopoljak/8012299 to your computer and use it in GitHub Desktop.
Executor wait for finished task by finish time ...
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
*
* @author DoDo <dopoljak@gmail.com>
*/
public class CompletitionService
{
public static void main(String[] args)
{
final Random random = new Random();
final String[] datas = { "data1", "data2", "data3", "data4", "data5", "data6" };
final ExecutorService pool = Executors.newFixedThreadPool(5);
final ExecutorCompletionService<String> completionService = new ExecutorCompletionService<String>(pool);
for (final String data : datas)
{
completionService.submit(new Callable<String>()
{
@Override
public String call() throws Exception
{
try
{
final int sleep = random.nextInt(1500);
Thread.sleep(sleep);
if(sleep < 1000) {
throw new Exception("Exception -> " + data);
}
return data;
}
catch (Exception e)
{
return e.getMessage();
}
}
});
}
try
{
for (int i = 0; i < datas.length; i++)
{
String complited = completionService.take().get();
System.out.println("Complited task : " + complited);
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Finished ...");
pool.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment