Reputation: 11455
When using Callable and Future in Java, what happens to the main thread when the other thread is executing the Callable. Is it sleeping and the other thread wakes it up when it has finished computing the value
import java.util.concurrent.*;
public class AddData {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
Future<Integer> result = service.submit(() -> 30+11);
System.out.println(result.get());
} finally {
if(service != null) service.shutdown();
}
}
}
With multithreading is it possible to see the current status(sleep, doing something) of thread like using VisualVM
Upvotes: 1
Views: 449
Reputation: 340350
The Answer by pveentjer is correct.
The dynamics of a situation such as your example will be more clear when Project Loom arrives. Preliminary builds are available now based on early-access Java 16, as the Java team invites feedback.
ExecutorService
is AutoClosable
In Project Loom, the ExecutorService
interface becomes AutoClosable
. This means it can be used with try-with-resources syntax.
After the code block of the try-with-resources, flow-of-control blocks to wait automatically until all submitted tasks are done.
No need to explicitly shutdown the executor service. The executor service gets shutdown automatically when its close
method is called after the try
block, as part of being AutoCloseable
.
Rather than block on Future#get
, you can collect your Future
objects as they are instantiated. Then later check them after the try
block.
import java.util.concurrent.*;
public class AddData
{
public static void main ( String[] args ) throws InterruptedException, ExecutionException
{
Future < Integer > additionFuture = null;
try (
ExecutorService service = Executors.newSingleThreadExecutor() ;
)
{
additionFuture = service.submit( ( ) -> 30 + 11 );
// … submit any further tasks for threaded work.
}
// At this point, flow-of-control in this thread (the main thread) blocks until all submitted tasks are done.
// When flow-of-control here resumes, the `ExecutorService` will have been automatically shutdown via its `close` method called as an `AutoCloseable`.
// Handle any `Future` objects you tracked.
if ( additionFuture.isCancelled() ) { … }
else { // Else not cancelled.
System.out.println( additionFuture.get() );
}
}
}
Upvotes: 1
Reputation: 11402
In your example the thread is going to block on the completion of the future. So on Linux it is removed from the run-queue of the scheduler and placed on a wait-queue where it will remain until future completes; then it will be reinserted into the scheduler and will get its chance to run. It will run very soon because it will be inserted at the beginning of the run-queue (look for Completely Fair Scheduler for more information).
Upvotes: 3