Added executor framework
This commit is contained in:
parent
d5d26c0445
commit
ff26c81b98
@ -0,0 +1,78 @@
|
||||
package com.hithomelabs.dsa.concurrency.ExecutorFramework;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class ExecutorInterfaces {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// * * An executor, is literally a function interface with a single method, replaces new Thread(runnable).start()
|
||||
// * * An implementation of executor, Executors is a helper class having more factory methods
|
||||
|
||||
Executor executor = Executors.newFixedThreadPool(2);
|
||||
executor.execute(() -> System.out.println("Hello World"));
|
||||
|
||||
// * * an executor does not shut down on it's own
|
||||
// * * ExecutorService provides more high level control
|
||||
|
||||
// * * Casting the Executor reference, to leverage the more extensive API
|
||||
ExecutorService executorService = (ExecutorService) executor;
|
||||
|
||||
// * * Executor Service provides a submit method:
|
||||
|
||||
Callable<String> task = () -> {
|
||||
System.out.println("will return hello after 2 seconds");
|
||||
Thread.sleep(2000);
|
||||
return "Hello";
|
||||
};
|
||||
|
||||
Future<String> futureHello = executorService.submit(task);
|
||||
try {
|
||||
System.out.println(futureHello.get());
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// * * Shuts down once already submitted tasks are complete
|
||||
executorService.shutdown();
|
||||
|
||||
// * * exploring different scenarios of shutdown.
|
||||
// * * Attempting to submit task after shutDown Initiated
|
||||
|
||||
System.out.println("Scenario 2:");
|
||||
executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
executorService.submit(task);
|
||||
executorService.submit(task);
|
||||
// * * Third task should be in the queue but must be completed
|
||||
executorService.submit(task);
|
||||
|
||||
executorService.shutdown();
|
||||
|
||||
// * * Uncomment to try awaitTermination
|
||||
// try {
|
||||
// if(executorService.awaitTermination(3, TimeUnit.SECONDS)){
|
||||
// System.out.println("Terminated in time");
|
||||
// }
|
||||
// else{
|
||||
// System.out.println("Waited 3 seconds");
|
||||
// }
|
||||
// } catch (InterruptedException e) {
|
||||
// System.out.println("Can't take this long");
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
|
||||
// * * Uncomment to try shutdown now
|
||||
// List<Runnable> couldNotComplete = executorService.shutdownNow();
|
||||
// couldNotComplete.stream().forEach(System.out::println);
|
||||
|
||||
try {
|
||||
// * * Task gets rejected
|
||||
executorService.submit(task);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Task gets rejected: reason: ");
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user