-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Tune single Thread into SingleThreadExecutor #5409
Comments
Wondering all tasks which are create by Means these tasks can't run in parallel? |
Yes, optimization is only for tasks that cannot be parallelized, such as |
Will it be possible that some tasks block the executor? Are there timeout or other ways we can do to terminate the abnormal task? |
In fact, most of the thread execution is a |
If thread executor process tasks one by one, will |
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.
The text was updated successfully, but these errors were encountered: