DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Efficient Task Management: Building a Java-Based Task Executor Service for Your Admin Panel
  • Managed Scheduled Executor Service vs EJB Timer
  • Deep Dive Into Java Executor Framework
  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService

Trending

  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Segmentation Violation and How Rust Helps Overcome It
  • Chaos Engineering for Microservices
  • The Modern Data Stack Is Overrated — Here’s What Works
  1. DZone
  2. Coding
  3. Java
  4. Guide to Java 8 Concurrency Using Executors

Guide to Java 8 Concurrency Using Executors

Here's an overview of the improvements Java 8 brought to concurrent programming with a focus on ExecutorService.

By 
Himani Arora user avatar
Himani Arora
·
May. 17, 18 · Tutorial
Likes (28)
Comment
Save
Tweet
Share
125.0K Views

Join the DZone community and get the full member experience.

Join For Free

Working with the Thread class in Java can be very tedious and error-prone. For this reason, the Concurrency API was introduced back in 2004 with the release of Java 5 and has been enhanced with every new Java release. The API is located in the package java.util.concurrent. It contains a set of classes that make it easier to develop concurrent (multi-threaded) applications in Java. 

The executor services are one of the most important parts 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:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);
});


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 implementations in the java.util.concurrent package:

  • ThreadPoolExecutor
  • ScheduledThreadPoolExecutor

Executors' factory class can also be used to create executor instances.

For example:

ExecutorService executorService1 = Executors.newSingleThreadExecutor();
ExecutorService executorService2 = Executors.newFixedThreadPool(5);


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.

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
    String threadName = Thread.currentThread().getName();
    &nbsp;System.out.println("Hello " + threadName);
});


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.

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


Callables are functional interfaces, but unlike Runnable, they return a value. A submit(callable task) method takes a Callable implementation

Callable<String> task = () -> "task 1 ";
ExecutorService executorService= Executors.newSingleThreadExecutor();
   Future future = executorService.submit(task);
System.out.println("value - "+future.get()); //returns task1


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.

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);


invokeAny(Collection<? extends Callable<T>> Tasks)

This method works slightly differently than invokeAll(). Instead of returning future objects, it blocks until the first callable terminates and returns the result of that callable.

ExecutorService executor = Executors.newWorkStealingPool();
 
List<Callable<String>> callables = Arrays.asList(
       ()->"task 1 completed",


ExecutorService Shutdown

ExecutorService provides two methods for this purpose:

  • shutdown() waits for currently running tasks to finish.
  • shutdownNow() interrupts all running tasks and shuts the executor down immediately.

References

  • Java 8 docs
  • Concurrency in Java

This article was first published on the Knoldus blog.

Java (programming language) Executor (software) Task (computing)

Published at DZone with permission of Himani Arora, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Efficient Task Management: Building a Java-Based Task Executor Service for Your Admin Panel
  • Managed Scheduled Executor Service vs EJB Timer
  • Deep Dive Into Java Executor Framework
  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!