vasanth0989 / prep-myself

0 stars 0 forks source link

Callable Future and Thread Pool using Executors #9

Open vasanth0989 opened 10 months ago

vasanth0989 commented 10 months ago

Callable Example

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class TestMain {

    public static void main(String[] args) throws Exception {
        // Anonymous Class
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(4000);
                return "Hello From Thread";
            }
        };
        FutureTask<String> futureTask = new FutureTask<>(callable);
        Thread th1 = new Thread(futureTask);
        th1.start();
        String output = futureTask.get();
        System.out.println("Output here:"+output);
    }
}
vasanth0989 commented 10 months ago

Executor's creating Thread Pool

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();
    }
}
vasanth0989 commented 10 months ago

Other Thread pool methods in Executor

    // 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();