Skip to content

Tune single Thread into SingleThreadExecutor #5409

@halibobo1205

Description

@halibobo1205

The SingleThreadExecutor pool consists of just one thread. It executes the submitted tasks sequentially. If an exception occurs and the thread gets terminated, a new one is created.

Thread vs. Single Thread Executor Service

1. Task Handling

Threads can only handle Runnable tasks, whereas a single thread executor service can execute both Runnable and Callable tasks. Therefore, using this, we can also run tasks that can return some value.

The submit() method in the ExecutorService interface takes either a Callable task or a Runnable task and returns a Future object. This object represents the result of an asynchronous task.

Also, a thread can handle just one task and exit. But a single thread executor service can handle a series of tasks and executes them sequentially.

2. Thread Creation Overhead

There is an overhead involved in creating threads. For instance, JVM needs to allocate memory. It impacts performance when threads are created repeatedly in the code. But in the case of a single thread executor service, the same worker thread is reused. Therefore, it prevents the overhead of creating multiple threads.

3. Memory Consumption

Thread objects take a significant amount of memory. Therefore, if we create threads for each asynchronous task, it can lead to OutOfMemoryError. But in a single thread executor service, the same worker thread is reused, which leads to less memory consumption.

4. Release of Resources

A thread releases resources once its execution completes. But in the case of executor service, we need to shut down the service or the JVM won't be able to shut down. Methods like shutdown() and shutdownNow() shutdown the executor service.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions