0

I want to know that when a program waits for Future object of one thread, will other threads continue their execution.

I have tried the below sample, it seems when my program is waiting for one thread, other threads are not continuing their execution. Please tell me whether this is correct or is there any issues with my code for handling threads.

ExecutorService executor = Executors.newFixedThreadPool(3);
for(int i=0; i<5 ;i++)
{
    Worker w = new Worker();
    Future<String> future = executor.submit(w);
    while(!future.isDone())
    {
        //Wait
    }
    String s = future.get();
    System.out.println(LocalDateTime.now()+" "+s);
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

Below is my worker class:

public class Worker implements Callable<String> {

@Override
public String call() throws Exception {
    // TODO Auto-generated method stub
    Thread.sleep(3000);
    return Thread.currentThread().getName();
}

}

I am getting the below results(Added date time to show that the results are not parallel):

2019-01-04T16:34:22.647 pool-1-thread-1
2019-01-04T16:34:25.661 pool-1-thread-2
2019-01-04T16:34:28.673 pool-1-thread-3
2019-01-04T16:34:31.685 pool-1-thread-1
2019-01-04T16:34:34.699 pool-1-thread-2
Antony Vimal Raj
  • 364
  • 3
  • 14
  • What makes you think waiting for a `Future` in one thread will cause **other** threads to wait? – Raedwald Jan 04 '19 at 12:40
  • That's almost the entire point of threads: They run independently of each other. Thread A can calculate something while thread B is waiting for keyboard/mouse input, while thread C is writing a file, while... The only exception is when you _explicitly_ synchronize them (e.g., thread C waits for thread A to place a result into a _[BlockingQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html)_.) – Solomon Slow Jan 05 '19 at 15:52

1 Answers1

2

The problem

You presented the code which from main thread perspective waits (2) for each execution before submitting new task (1). In other words: in main thread you submit the task, wait for complete execution in main thread and submit next task after.

ExecutorService executor = Executors.newFixedThreadPool(3);
for(int i=0; i<5 ;i++)
{
    Worker w = new Worker();
    Future<String> future = executor.submit(w); // (1)
    while(!future.isDone()) // (2)
    {
        //Wait
    }
    String s = future.get();
    System.out.println(LocalDateTime.now()+" "+s);
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

Solution

To solve the issue you should (from main thread perspective) submit all tasks without waiting and then wait for results from executor service.

Example: https://stackoverflow.com/a/49746114/1815881 You can construct all tasks then call invokeAll() in ExecutorService.

Athlan
  • 6,389
  • 4
  • 38
  • 56