Updated February 10, 2023
Introduction to Java 8 ExecutorService
Java 8 executorservice is nothing but the interface that allows us to execute tasks asynchronously on threads. The interface is present in the package name as java util concurrent. The executorservice of java 8 helps us to maintain the threads pool and assign the task to that thread. It provides the facility to queue the task until a free thread is available for operations.
Key Takeaways
- It extends the executor by adding methods that helps to control and manage execution.
- The shutdownNow method prevents tasks from waiting to start and attempts to kill currently running tasks. At the time of termination, the executor is not carrying out any active tasks.
What is Java 8 ExecutorService?
In java 8 executor provides methods to manage termination. We are also using methods that produce a tracking progress feature of more than one task, which was asynchronous. It is shutting down, and at the same time, it will reject new tasks. There are two methods used to shut down the ExecutorService in java. The first method is shutdown() which allows to execution of previously submitted tasks before terminating.
Basically, the ExecutorService in Java 8 extends the executor by adding methods to control and manage thread execution. The execution mechanism of this service is defined as asynchronous. In Java 8, the ExecutorService is important for thread management. By using the executor service, we can manage our thread at the time of submission.
How to Create Java 8 ExecutorService?
We can create the ExecutorService to create a single thread scheduled pool or a pool of threads. The executor class in Java 8 provides factory methods for instantiating the ExecutorService. The ExecutorService is used to manage and control the threads.
The ExecutorService performs the following tasks as follows:
- Creation of thread: In java 8, ExecutorService provides multiple methods to create threads. This will help us to run the application concurrently.
- Management of thread: As we all know, the Java ExecutorService also helps us in managing threads throughout their life cycle. So, before submitting our task for execution, we don’t need to check whether our thread is busy, dead, or active.
- Execution of task and submission of task: In Java 8, the ExecutorService also provides methods for submitting tasks to the thread pool. It also provides us with the ability to determine whether or not our thread is running.
In the below example, we are creating the simple execution service, which assigns tasks for the ExecutorService by using the execute method. In java 8 executor service, execute method is taking the runnable object and performs the task asynchronously. While making calls to the method of execute, we can call the shutdown method, which blocks other tasks as follows.
Code:
import java.util.concurrent.*;
public class Main
{
public static void main(String[] args) {
ExecutorService exeSer1 = Executors.newSingleThreadExecutor ();
exeSer1.execute (new Runnable ()
{
@Override
public void run() {
System.out.println ("Execute service creation");
}
});
exeSer1.shutdown ();
}
}
Output:
In the below example, we are creating multiple threads at the time of creating executor service. In the below example, we can see that the thread is executed as per the order that we have defined.
Code:
import java.util.concurrent.*;
public class ExeSer {
public static void main(String[] args)
{
CountDownLatch T1 = new CountDownLatch(5);
CountDownLatch T2 = new CountDownLatch(5);
CountDownLatch T3 = new CountDownLatch(5);
CountDownLatch T4 = new CountDownLatch(5);
ExecutorService exe = Executors.newFixedThreadPool(2);
System.out.println("Executor service starting");
exe.execute(new MyThread(T1, "ABC"));
exe.execute(new MyThread(T2, "BCD"));
exe.execute(new MyThread(T3, "CDE"));
exe.execute(new MyThread(T4, "DEF"));
try {
T1.await();
T2.await();
T3.await();
T4.await();
}
catch(InterruptedException e) {
System.out.println(e);
}
es.shutdown();
System.out.println("Executed");
}
}
class ExeThr implements Runnable {
String stud_name;
CountDownLatch la;
MyThread(CountDownLatch la, String stud_name)
{
this.stud_name = stud_name;
this.la = la;
new Thread(this);
}
public void run()
{
for(int i = 1; i < 5; i++) {
System.out.println(stud_name + ": " + i);
la.countDown();
}
}
}
Output:
Methods
There are eight types of methods available for ExecutorService as follows:
- awaitTermination: This method waits for all the tasks to complete the execution; while finding the request of shutdown, it will wait for the argument of the time limit.
- invokeAll: This method executes all the tasks which contain in the collection. A future object containing the status is returned.
- invokeAny: This method executes all the tasks which contains in the collection. Completion of one task will return the result.
- isShutdown: It will tell us whether or not our executor has been shut down. The Boolean value will be returned.
- isTerminated: This method checks whether all the methods are completed or not after shutdown. It will return the Boolean value.
- Shutdown: It will cause all threads to stop their current execution. It will start and reject new tasks.
- shutdownNow: This method forcefully terminates all the tasks. It will return the list of tasks in a steady state.
- Submit: This method adds the task that returns the result list of the task that was executed for execution.
The below example shows methods of java ExecutorService as follows. In the below example, we are using shutdown service as follows:
Code:
import java.util.concurrent.*;
public class ExeMethod {
public static void main(String[] args){
ExecutorService exe = Executors.newSingleThreadExecutor ();
exe.submit (new Runnable () {
@Override
public void run() {
System.out.println("Method of executor service");
}
});
}
}
Output:
Examples of Java 8 ExecutorService
Given below are the examples mentioned:
Example #1
In the below example, we are creating the thread pool of five threads as follows.
Code:
import java.util.concurrent.*;
public class Exp
{
public static void main(String[] args)
{
ExecutorService exe = Executors.newFixedThreadPool (5);
exe.submit (() -> System.out.println ("Run task"));
Future<Integer> ftask1 = exe.submit (() ->
{
System.out.println ("Call task");
return 1 + 1;
});
try {
otherTask ("Before Res");
Integer res = ftask1.get (5, TimeUnit.SECONDS);
System.out.println ("Get res : " + res);
otherTask ("After Res");
} catch (InterruptedException e) {
e.printStackTrace ();
} catch (ExecutionException e) {
e.printStackTrace ();
} catch (TimeoutException e)
{
e.printStackTrace ();
} finally {
exe.shutdown ();
}
}
private static void otherTask(String stud_name)
{
System.out.println ("Other work " + stud_name);
}
}
Output:
Example #2
In the below example, we are using invokeAll method as follows.
Code:
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Exp {
public static void main(String[] args){
ExecutorService exe = Executors.newCachedThreadPool ();
List<Callable<Integer>> listOfCallable = Arrays.asList (
() -> 14,
() -> 31,
() -> 26);
try {
List<Future<Integer>> futures = exe.invokeAll (listOfCallable);
int sum = futures.stream ().map(f ->
{
try {
return f.get ();
} catch (Exception e)
{
throw new IllegalStateException (e);
}
}).mapToInt (Integer::intValue).sum ();
System.out.println (sum);
} catch (InterruptedException e) {
e.printStackTrace ();
} finally {
exe.shutdown ();
}
}
}
Output:
FAQs
Given below are the FAQs mentioned:
Q1. What is the use of ExecutorService in java?
Answer: The ExecutorService is used to manage and control the thread execution. It is an interface that executes tasks on the thread.
Q2. How can we use the java 8 ExecutorService?
Answer: We use it for creating a pool of threads, single threads, or a scheduled thread pool. The class of executor provides the factory methods.
Q3. Which methods we are using for assigning tasks to ExecutorService?
Answer: We are using the below methods at the time of assigning tasks to ExecutorService i.e. execute, invokeAny, invokeAll, and submit.
Conclusion
Java 8 ExecutorService is shutting down and rejecting new tasks at the same time. In Java, there are two methods for terminating the ExecutorService. It is nothing but an interface that allows us to execute tasks asynchronously on threads. The java 8 executorservice interface is present in the package name as java util concurrent.
Recommended Articles
This is a guide to Java 8 ExecutorService. Here we discuss the introduction, how to create java 8 ExecutorService, methods, and examples. You may also have a look at the following articles to learn more –