Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading