Waiting for background tasks to finish using the CompletableFuture class in Java

Introduction

In this post we saw how to wait for a number background tasks to finish using the CountDownLatch class. The starting point for the discussion was the following situation:

Imagine that you execute a number of long running methods. Also, let’s say that the very last time consuming process depends on the previous processes, let’s call them prerequisites. The dependence is “sequential” meaning that the final stage should only run if the prerequisites have all completed and returned. The first implementation may very well be sequential where the long running methods are called one after the other and each of them blocks the main thread.

However, in case the prerequisites can be executed independently then there’s a much better solution: we can execute them in parallel instead. Independence in this case means that prerequisite A doesn’t need any return value from prerequisite B in which case parallel execution of A and B is not an option.

In this post we’ll look at an alternative solution using the CompletableFuture class. It is way more versatile than CountDownLatch which is really only sort of like a simple lock object. CompletableFuture offers a wide range of possibilities to organise your threads with a fluent API. Here we’ll start off easy with a simple application of this class.

Read more of this post

Advertisement

Sharing primitives across threads in Java using atomic objects

Threading and parallel execution are popular choices when making applications more responsive and resource-efficient. Various tasks are carried out on separate threads where they either produce some result relevant to the main thread or just run in the background “unnoticed”. Often these tasks work autonomously meaning they have their own set of dependencies and variables. That is they do not interfere with a resource that is common to 2 or more threads.

However, that’s not always the case. Imagine that multiple threads are trying to update the same primitive like an integer counter. They perform some action and then update this counter. In this post we’ll see what can go wrong.

Read more of this post

Sharing numeric values across threads using Java 8 LongAdder

In this post we saw how to share primitive values across threads using the various atomic objects in the java.util.concurrent.atomic package. The example code demonstrated the AtomicInteger object which is the thread-safe variant of a “normal” integer. Mathematical operations like adding a value to an integer are carried out atomically for that object. This means that the low-level instructions involved in adding two integers are carried out as one unit without the risk of another interfering thread. The same package includes atomic versions of other primitive values such as AtomicBoolean or AtomicLong.

In this post we’ll take a quick look at an addition in Java 8 relevant to sharing integers, longs and doubles.

Read more of this post

Sharing primitives across threads in Java using atomic objects

Threading and parallel execution are popular choices when making applications more responsive and resource-efficient. Various tasks are carried out on separate threads where they either produce some result relevant to the main thread or just run in the background “unnoticed”. Often these tasks work autonomously meaning they have their own set of dependencies and variables. That is they do not interfere with a resource that is common to 2 or more threads.

However, that’s not always the case. Imagine that multiple threads are trying to update the same primitive like an integer counter. They perform some action and then update this counter. In this post we’ll see what can go wrong.

Read more of this post

Getting the result of the first completed parallel task in Java

In this post we saw how to delegate one or more parallel tasks to different threads and wait for all of them to complete. We pretended that 4 different computations took 1,2,3 and respectively 4 seconds to complete. If we execute each calculation one after the other on the same thread then it takes 10 seconds to complete them all. We can do a lot better by assigning each operation to a separate thread and let them run in parallel. The Future and Callable of T objects along with a thread pool make this very easy to implement.

There are situations where we only need the result from 1 parallel operation. Imagine that it’s enough to complete 1 of the four computations in the example code so that our main thread can continue. We don’t know how long each operation will take so we let them have a race. The one that is executed first returns its value and the rest are interrupted and forgotten. We’ll see how to achieve that in this post.

Read more of this post

Getting a result from a parallel task in Java using CompletableFuture

In this post we saw how to start several processes on different threads using the CompletableFuture class. The example concentrated on methods with no return value. We let CompletableFuture finish the tasks in parallel before continuing with another process.

In this post we’ll see a usage of CompletableFuture for functions with a return value. We’ll reuse several elements we saw in the post that concentrated on the Future class.

Read more of this post

Running a task on a different thread in Java 8

Occasionally it can be worth putting a task on a different thread so that it doesn’t block the main thread. Examples include a task that analyses heavy files, a task that sends out emails etc. If we put these tasks on a different thread and don’t wait for it to return a result then it’s called the fire-and-forget pattern. We start a new thread and let it run in the background. The task on the different thread is expected to carry out its functions independently of the main thread.

Let’s imagine that the following greetCustomer method is something we want to run on separate thread so that the main thread is not blocked:

Read more of this post

Getting a result from a parallel task in Java using CompletableFuture

In this post we saw how to start several processes on different threads using the CompletableFuture class. The example concentrated on methods with no return value. We let CompletableFuture finish the tasks in parallel before continuing with another process.

In this post we’ll see a usage of CompletableFuture for functions with a return value. We’ll reuse several elements we saw in the post that concentrated on the Future class.

Read more of this post

Summary of thread-safe collections in .NET

The System.Collections.Concurrent namespace has 4 thread-safe collections that you can use in multi-threaded applications. The starting point is that you have a multi-threaded app where the same collection needs to be accessed by different threads. In that case the well-know collection types, like HashSet, List, Dictionary etc. simply won’t be enough.

If many different threads have access to the same resource then there’s no guarantee on the state of that resource in the moment a thread accesses it in some way: deletion, lookup, insertion or modification. Another thread may have accessed the same resource just milliseconds before that and the other thread will access the resource under the wrong assumptions. You’ll end up with buggy code with unpredictable results and ad-hoc fixes and patches that probably won’t solve the root of the problem.

Read more of this post

Waiting for background tasks to finish using the CompletableFuture class in Java

Introduction

In this post we saw how to wait for a number background tasks to finish using the CountDownLatch class. The starting point for the discussion was the following situation:

Imagine that you execute a number of long running methods. Also, let’s say that the very last time consuming process depends on the previous processes, let’s call them prerequisites. The dependence is “sequential” meaning that the final stage should only run if the prerequisites have all completed and returned. The first implementation may very well be sequential where the long running methods are called one after the other and each of them blocks the main thread.

However, in case the prerequisites can be executed independently then there’s a much better solution: we can execute them in parallel instead. Independence in this case means that prerequisite A doesn’t need any return value from prerequisite B in which case parallel execution of A and B is not an option.

In this post we’ll look at an alternative solution using the CompletableFuture class. It is way more versatile than CountDownLatch which is really only sort of like a simple lock object. CompletableFuture offers a wide range of possibilities to organise your threads with a fluent API. Here we’ll start off easy with a simple application of this class.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: