Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

 1. Overview

Multithreading and parallel processing are crucial concepts in modern application development. In Java, the Executor framework provides a way to manage and control the execution of concurrent tasks efficiently. The ExecutorService interface is at the core of this framework, and it provides two commonly used methods for submitting tasks to be executed: submit() and execute().

In this article, we’ll explore the key differences between these two methods. We’ll look at both submit() and execute() using a simple example where we want to simulate a task of calculating the sum of numbers in an array using a thread pool.

2. Usage of ExecutorService.submit( )

Let’s start with the submit() method first which is widely used in the ExecutorService interface. It allows us to submit tasks for execution and returns a Future object that represents the result of the computation.

This Future then allows us to obtain the result of the computation, handle exceptions that occur during task execution, and monitor the status of the task. We can call get() in the Future to retrieve the result or exceptions.

Let’s start by initializing the ExecutorService:

ExecutorService executorService = Executors.newFixedThreadPool(2);

Here, we’re initializing the ExecutorService with a fixed thread pool of size 2. This creates a thread pool that utilizes a fixed number of threads operating off a shared unbounded queue. In our case, at any point, at most two threads will be active processing tasks. If more tasks are sent while all existing tasks are being processed, they will be held in the queue until a processing thread becomes free.

Next, let’s create a task using Callable:

Callable<Integer> task = () -> {
    int[] numbers = {1, 2, 3, 4, 5};
    int sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    return sum;
};

Importantly, here, the Callable object represents the task that returns a result and may throw an exception. In this case, it represents a task that another thread can execute and return a result or may throw exceptions. This Callable calculates the sum of integers in an array and returns the result.

Now that we’ve defined the task as Callable, let’s submit this task to the ExecutorService:

Future<Integer> result = executorService.submit(task);

Simply put, the submit() method takes the Callable task and submits it for execution by the ExecutorServiceIt returns a Future<Integer> object that represents the future result of the computation. Overall, executorService.submit() is a way to asynchronously execute a Callable task using ExecutorService allowing for concurrent execution of tasks and obtaining their results via the returned Future

Finally, let’s check the result:

try {
    int sum = result.get();
    System.out.println("Sum calculated using submit:" + sum);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}

Here, get() retrieves the result of the task execution. In this case, it fetches the sum calculated by the task and prints it. However, it’s important to note that the get() method is a blocking call and waits if the result isn’t available yet, potentially causing the thread to pause until the result is ready. It can also throw exceptions like InterruptedException or ExecutionException if the computation encounters issues while running.

Finally, let’s shut down the ExecutorService:

executorService.shutdown();

This shuts down the ExecutorService after the task has completed execution and releases any resources used by the service.

3.  Usage of ExecutorService.execute( )

The execute() method is a simpler method, defined in the Executor interface which is a parent interface of ExecutorService. It’s used to submit tasks for execution but doesn’t return a Future. This means that we cannot obtain the result of the task or handle exceptions directly through the Future object.

It’s suitable for scenarios where we don’t need to wait for the result of the task and we don’t expect any exceptions. These tasks are executed for their side effect.

Like before, we’ll create an ExecutorService with a fixed thread pool of 2.  However, we’ll create a task as Runnable instead:

Runnable task = () -> {
    int[] numbers = {1, 2, 3, 4, 5};
    int sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    System.out.println("Sum calculated using execute: " + sum);
};

Importantly, the task doesn’t return any result; it simply calculates the sum and prints it inside the task. We’ll  now submit the Runnable task to the ExecutorService:

executorService.execute(task);

This remains an asynchronous operation, indicating that one of the threads from the thread pool executes the task.

4. Conclusion

In this article, we looked at the salient features and usages of submit() and execute() from the ExecutorService interface. In summary, both of these methods offer a way to submit tasks for concurrent execution, but they differ in their handling of task results and exceptions.

The choice between submit() and execute() depends on specific requirements. If we need to obtain the result of a task or handle exceptions, we should use submit(). On the other hand, if we have a task that doesn’t return a result and we want to fire it and forget it, execute() is the right choice.

Moreover, if we’re working with a more complex use case and need the flexibility to manage tasks and retrieve results or exceptions, submit() is the better choice.

As always, the complete code for this article is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!