

Guide to Java 8 Concurrency API using Executors
source link: https://blog.knoldus.com/guide-java-8-concurrency-using-executors/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Guide to Java 8 Concurrency API using Executors
Reading Time: 3 minutes
Working with the Thread class in Java can be very tedious and error-prone. Due to this reason, Concurrency API was introduced back in 2004 with the release of Java 5 and then enhanced with every new Java release.The API is located in package java.util.concurrent. It contains a set of classes that make it easier to develop concurrent (multithreaded) applications in Java.
The executor services are one of the most important part of the Concurrency API. With the help of this guide, you can learn how to execute code in parallel via tasks and executor services in Java 8.
ExecutorService
The Concurrency API introduces the concept of an ExecutorService as a higher level replacement for working with threads directly.
Executors are capable of managing a pool of threads, so we do not have to manually create new threads and run tasks in an asynchronous fashion.
Have a look at a simple Java ExecutorService:
[sourcecode language=”java”]
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println(“Hello ” + threadName);
});
[/sourcecode]
Here, It submits a Runnable task for execution and returns a Future representing that task. Since Runnable is a functional interface we are utilizing Java 8 lambda expressions to print the current threads name to the console.
ExecutorService Implementation
Since ExecutorService is an interface, it has to be implemented in order to make any use of it. The ExecutorService has the following implementation in the java.util.concurrent package:
- ThreadPoolExecutor
- ScheduledThreadPoolExecutor
Executors factory class can also be used to create executor instances.
For eg.-
[sourcecode language=”java”]
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
ExecutorService executorService2 = Executors.newFixedThreadPool(5);
[/sourcecode]
Delegating tasks to ExecutorService
Below are few of the different ways that can be used to delegate tasks for execution to an ExecutorService:
- execute(Runnable command)
- submit(Callable task)
- submit(Runnable task)
- invokeAny(Collection<? extends Callable<T>> tasks)
- invokeAll(Collection<? extends Callable<T>> tasks)
execute(Runnable command)
This method takes a java.lang.Runnable object, and executes it asynchronously.
[sourcecode language=”java”]
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
String threadName = Thread.currentThread().getName();
System.out.println(“Hello ” + threadName);
});
[/sourcecode]
submit(Callable task) and submit(Runnable task)
The submit(Runnable task) method takes a Runnable implementation and returns a Future object. which can be used to check if the Runnable as finished executing.
[sourcecode language=”java”]
Runnable task=()->{
System.out.println(“runnable task”);
};
ExecutorService executorService= Executors.newSingleThreadExecutor();
Future future= executorService.submit(task);
System.out.println(“value – “+future.get()); //returns null if the task has finished successfully
[/sourcecode]
Callables are functional interfaces but unlike Runnable they return a value. submit(callable task) method takes a Callable implementation
[sourcecode language=”java”]
Callable<String> task = () -> “task 1 “;
ExecutorService executorService= Executors.newSingleThreadExecutor();
Future future= executorService.submit(task);
System.out.println(“value – “+future.get()); //returns task1
[/sourcecode]
invokeAll(Collection<? extends Callable<T>> tasks)
This method supports batch submitting of multiple callables at once. It accepts a collection of callables and returns a list of futures.
[sourcecode language=”java”]
ExecutorService executor = Executors.newFixedThreadPool(1);
List<Callable<String>> callables = Arrays.asList(
() -> “t1”,
() -> “t2”
);
executor.invokeAll(callables)
.stream()
.map(future -> {
try {
return future.get();
}
catch (Exception e) {
throw new IllegalStateException(e);
}
})
.forEach(System.out::println);
[/sourcecode]
invokeAny(Collection<? extends Callable<T>> tasks)
This method works slightly different to invokeAll(). Instead of returning future objects it blocks until the first callable terminates and returns the result of that callable.
[sourcecode language=”java”]
ExecutorService executor = Executors.newWorkStealingPool();
List<Callable<String>> callables = Arrays.asList(
()->”task 1 completed”,
[/sourcecode]
ExecutorService shut down
ExecutorService provides two methods for this purpose:
- shutdown() waits for currently running tasks to finish
- shutdownNow() interrupts all running tasks and shut the executor down immediately.
References
Recommend
-
49
A few weeks ago, the member of the C++ standardisation committee Felix Petriconi wrote me an E-Mail. He said my article about std::future Extensions
-
54
Executors是一个线程池的工厂类,提供各种有用的线程池的创建,使用得当,将会使我们并发编程变得简单!今天就来聊聊这个工厂类的艺术吧! Executors只是Executor框架的主要成员组件之一,为java的异步任务调度执行提供了重要的...
-
41
看阿里巴巴开发手册并发编程这块有一条:线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,通过源码分析禁用的原因 写在前面 首先感谢大家在盖楼的间隙阅读本篇文章,通过阅读本篇文章你将了解到: 线程池的定义 Exec
-
16
一. 序 在 Java 领域内,我们使用多线程的方式...
-
27
我们先看 Java 开发手册上说的: 我们可以看一下源码:
-
8
Reading Time: 2 minutes What is executor service? Executor service is a framework which helps us to run the task asynchronously with their own thread pool. Future uses executor service to execute their task separately. ...
-
8
C++ Executors: the Good, the Bad, and Some Examples Executors ar...
-
9
In this tutorial, let’s look at various ways we can stop or cancel tasks running in Executor and
-
6
提供一些工厂方法和工具类方法. 给Executor,ExecutorService,ScheduledExecutorService和ThreadFacotry使用. Callable类在这里定义. 这个类提供以下几种方法: 用一些常...
-
5
Executors: a Change of Perspective In my last Overload article,...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK