javamultithreadingexecutorserviceexecutor

Callable thread for singleThreadExecutor is working as synchronously


I have tested the below callable sample code

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> futureResMap = executorService.submit(new Callable<String>() {
    @Override
    public String call() throws Exception {
        return "thread:1";
    }
});
executorService.shutdown();
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("Thread response:"+futureResMap.get());
System.out.println("4");
System.out.println("5");

and gets the output always as below

1
2
3
Thread response:thread:1
4
5

Which means Callable with single thread executor runs synchronously always.

When i tried for runnable as below

ExecutorService executorService = Executors.newSingleThreadExecutor();  
executorService.execute(new Runnable() {
    @Override
    public void run() {
        System.out.println("Thread response:thread:1");
    }
});
executorService.shutdown();
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("5");

Which provides different output every time.

Run:1

1
2
Thread response:thread:1
3
4
5

Run 2:

1
2
3
Thread response:thread:1
4
5

So according to my point of view for Callable with single thread executor is working as synchronous. Callable is mostly for multithreaded implementation. Is my understanding correct?


Solution

  • Method get of Future class retrives result of a task, waiting endlessly if it is not avalible.