Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you always use an ExecutorService instead of starting your own thread?

With JDK >= 1.5, should the preferred way to start a thread always be an Executor or Executor Service, or are there still reasons to prefer to use a Thread.start if you don't need what an ExecutorService provides?

For syncronized, I used to think that using the new Lock implemenations was preferred, until I was explained otherwise. So I'm wondering the same thing about Executors. Are they just a way of handling more complex cases, or should they be the standard choice?

like image 485
Yishai Avatar asked Jul 13 '10 12:07

Yishai


People also ask

What are the advantages of using ExecutorService instead of creating threads directly?

ExecutorService abstracts away many of the complexities associated with the lower-level abstractions like raw Thread . It provides mechanisms for safely starting, closing down, submitting, executing, and blocking on the successful or abrupt termination of tasks (expressed as Runnable or Callable ).

Why do we need ExecutorService in Java?

The ExecutorService helps in maintaining a pool of threads and assigns them tasks. It also provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available.

What is the use of ExecutorService?

Interface ExecutorService. An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks. An ExecutorService can be shut down, which will cause it to reject new tasks.

Can I use Callable thread without ExecutorService?

Yes you can use the call() method of a Callable or the run() method of a Runnable from your own thread directly.


1 Answers

Java Concurrency in Practice at least clearly states in section 6.2.:

The primary abstraction for task execution in the Java class libraries is not Thread, but Executor. [...]

Using an Executor is usually the easiest path to implementing a producer-consumer design in your application.

like image 95
Péter Török Avatar answered Oct 16 '22 17:10

Péter Török