Home > Enterprise >  What is the use of java.util.concurrent.FutureTask if it blocks main?
What is the use of java.util.concurrent.FutureTask if it blocks main?

Time:04-30

I am rather new to learning java.util.concurrent. While implementing a basic program (below) it's clear that the main thread waits for Callable to return a value.

    public class FutureTaskTutorial {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask(new MyCallable());
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get());
        System.out.println("main thread done!");
    }
}

class MyCallable implements Callable<String>{

    @Override
    public String call() throws Exception {
        Thread.sleep(5000);
        return "Callable task done!";
    }
}

Output: <after 5 seconds>

Callable task done!

main thread done!

My question is: If my callable is going to block main thread and asynchronous behaviour is not going to be achieved, what is the point of using a FutureTask?

CodePudding user response:

FutureTask#get may be blocking, however the usecase of FutureTasks is to periodically check if they are done while still executing the rest of the main-method. For example:

FutureTask<Object> task = new FutureTask<>( () ->
{
  Thread.sleep( 1_000 );
  return "Hello world";
} );

Executors.newSingleThreadExecutor().execute( task );

boolean doMainWork = true;

while( doMainWork )
{
  if( task.isDone() )
  {
    System.out.println( task.get() );
    doMainWork = false;
  }
  System.out.println( "Main working "   task.isDone() );
  Thread.sleep( 500 );
}
  • Related