Skip to content

Instantly share code, notes, and snippets.

@arunma
Created September 15, 2012 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arunma/3729309 to your computer and use it in GitHub Desktop.
Save arunma/3729309 to your computer and use it in GitHub Desktop.
Thread Pool Executor using submit()
package me.rerun.incubator;
import java.util.concurrent.Callable;
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;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorSubmit {
public void runApp() throws InterruptedException, ExecutionException{
//holder for the total sum
AtomicInteger sum=new AtomicInteger();
//Use the factory method of Executors
ExecutorService executorService=Executors.newFixedThreadPool(10);
Future<AtomicInteger> future = null;
for (int count = 0; count <= 100; count++) {
future = executorService.submit(getInstanceOfCallable(count,sum));
//prints intermediate sum
try {
System.out.println("Status of future : " + future.isDone() +". Result of future : "+future.get(1000, TimeUnit.MILLISECONDS).get());
} catch (TimeoutException e) {
System.out.println("<IGNORE> Timeout exception for count : "+count);
//e.printStackTrace();
}
//System.out.println("Result of future : "+future.get().get() +".Status of future : " + future.isDone());
}
executorService.shutdown();
if (executorService.awaitTermination(10, TimeUnit.SECONDS)){
System.out.println("All threads done with their jobs");
}
//exec
System.out.println("Final Sum : "+sum);
}
//Adds count to the sum and returns the reference of the sum as the result
private Callable<AtomicInteger> getInstanceOfCallable(final int count, final AtomicInteger sum) {
Callable<AtomicInteger> clientPlanCall=new Callable<AtomicInteger>(){
public AtomicInteger call() {
sum.addAndGet(count);
//System.out.println("Intermediate sum :"+sum);
return sum;
}
};
return clientPlanCall;
}
public static void main(String[] args) throws ExecutionException {
try {
new ExecutorSubmit().runApp();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment