diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/ExecutorFramework/ExecutorInterfaces.java b/src/main/java/com/hithomelabs/dsa/concurrency/ExecutorFramework/ExecutorInterfaces.java new file mode 100644 index 0000000..5fd6971 --- /dev/null +++ b/src/main/java/com/hithomelabs/dsa/concurrency/ExecutorFramework/ExecutorInterfaces.java @@ -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 task = () -> { + System.out.println("will return hello after 2 seconds"); + Thread.sleep(2000); + return "Hello"; + }; + + Future 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 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()); + } + } + +}