Skip to content

Instantly share code, notes, and snippets.

@nate-getch
Created October 8, 2018 19:25
Show Gist options
  • Save nate-getch/8003a3fa9912fd172b3a4bed6f78cc3e to your computer and use it in GitHub Desktop.
Save nate-getch/8003a3fa9912fd172b3a4bed6f78cc3e to your computer and use it in GitHub Desktop.
Java ExecutorService example
package nd.financial.fw.subject;
import java.util.ArrayList;
import java.util.List;
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;
public class ExecutorServiceApp {
public static void main(String args[]){
ExecutorService executorService = Executors.newFixedThreadPool(10);
///////////////////////////////////////////////////////////
Callable<String> c1 = () -> {
return "c1 executed";
};
Future<String> f1 = executorService.submit(c1);
try {
System.out.println(f1.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
///////////////////////////////////////////////////////////
List<Callable<String>> callableList = new ArrayList<>();
Callable<String> callable = () -> {
return "hello ...";
};
callableList.add(callable);
Callable<String> callable2 = () -> {
return "callable2 executed";
};
callableList.add(callable2);
try {
List<Future<String>> futureList = executorService.invokeAll(callableList, 50000,
TimeUnit.MILLISECONDS);
futureList.stream().forEach(future -> {
if (!future.isCancelled() && future.isDone())
try {
System.out.print(future.get());
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (InterruptedException e1) {
e1.printStackTrace();
}
///////////////////////////////////////////////////////////////////
executorService.execute(new Runnable() {
public void run() {
System.out.println("\nAsynchronous task via Runnable");
}
});
///////////////////////////////////////////////////////////////////
executorService.shutdown();
}
}
@nate-getch
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment