TechieHints SOFTWARE

Usage of ExecutorService – java.util.concurrent

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background.

An ExecutorService is thus very similar to a thread pool. In fact, the implementation of ExecutorService present in the java.util.concurrent package is a thread pool implementation.

The interface ExecutorService extends Executor and provides methods to manage the lifecycle of an Executor like:

  • means to initiate thread(s) invocation.
  • means to schedule thread for any interval or any particular time using ScheduledExecutorService.
  • means to provide status of the thread run using (Future ).
  • means to terminate the thread(s) execution(forcibly as well as safely).

    Future object can be used for tracking the progress of one or more asynchronous tasks.

Java Callable tasks return java.util.concurrent.Future objects. 

Java Future provides a cancel() method to cancel the associated Callable task. This is an overloaded version of the get() method, where we can specify the time to wait for the result. It’s useful to avoid a current thread getting blocked for a longer time. Please note that the get method is a synchronous method. Until the callable finishes its task and returns a value, it will wait for a callable. There are also isDone() and isCancelled() methods to find out the current status of an associated Callable task.

 

Leave a comment