Open vasanth0989 opened 10 months ago
import java.util.concurrent.*;
public class TestMain {
public static void main(String[] args) throws Exception {
// Thread pool
// By Default Executor service is backed up by LinkedBlockingQueue
// The Threads inside Thread pool will always be in a runnable state
// So that each time we won't pay for the Thread creation task as it is an expensive one.
ExecutorService executorService = Executors.newFixedThreadPool(4);
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(4000);
return "Coming From Future";
}
};
Future<String> future = executorService.submit(callable);
// future.get() is a blocking call meaning the thread which invokes the .get() call will be blocked until it gets the response
// this is similar to the join() methods we saw in Threads
System.out.println("Getting the value from the future:"+future.get());
// If you are creating an Executor always remember to shut down it
// Else your JVM will not exit
// By default Threads inside Executor are all non-daemon threads
executorService.shutdown();
}
}
// we have to use this cautiously because for every task a new Thread gets created
// Problem with that is, your JVM can run into OutOfMemory Error since we don't have control that how many threads can be created.
// It is always best to use FixedThreadPool
ExecutorService executorService = Executors.newCachedThreadPool();
// This ExecutorService will always create a single Thread
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable Example