Concurrency in Java: Basic way of use

Daniel S. Blanco
2 min readJun 7, 2020

--

Concurrency could be a headache if we need to work at a low level. But if we only need to call another thread and wait for its response, it could be very easy.

For that kind of work, we can rely on ExecutorService, Callable and Future interfaces. These interfaces will allow us to perform operations in parallel threads and manage the result of those operations easily.

ExecutorService
It will allow us to create parallel execution thread/s. These threads will be able to execute a Callable/Runnable instance. For Runnable it will use the execute method and for Callable the submit method.

It will also allow us to know the status of the execution threads, stop them or wait for their termination.

Callable
It will allow us to create a logic and that we can be able to invoke it through an ExecutorService. The main difference with the most known Runnable interface is that with Callable we will be able to return a value associated to the logic that we have made.

Future
It allows us to manage the result of an asynchronous operation. It puts at our disposal different methods to check the result of the operation and its flow.

For example, with isDone, we will check if the associated thread has already ended. With isCancelled we can check if the if it has been cancelled the thread associated. And with get, you can obtain the value of the asynchronous operation.

Executors
This is properly an utility class, how you can see by the name. This utility provides us with different methods to create a thread pool: simple, cached, parameterized, etc.

Now let’s see everything in one simple example. In it, we will create a basic execution thread pool that will call a ‘complicated’ method in a parallel thread.

After calling to this secondary and complicated thread, the main thread will wait for it. And we will be asking continuously if the secondary thread has finished thanks to the isDone method. Finally, we’ll get its value asocciated to the second thread with Future get method. Everything, after a positive response.

This program will show the next execution:

Waiting for future value
Waiting for future value
Waiting for future value
Waiting for future value
End tough operation finally with result: 0.9030054906859435

--

--

No responses yet