Yishai
Yishai

Reputation: 91871

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?

Upvotes: 15

Views: 2486

Answers (3)

Riduidel
Riduidel

Reputation: 22292

Personally, since Java 5, I've completely left over Thread and ThreadGroup, as they provide way less customization and functionality than ExecutorService.

When using ExecutorService, I know I can use Callable, I know I can (with a little overhead) schedule repeated tasks. As a consequence, I consider direct instantiation of Thread objects deprecated code, as Vector and Hashtable are.

Upvotes: 11

Jeremy
Jeremy

Reputation: 607

Writing correct multi-threaded code is very difficult. The beauty of the Executor framework is that it implements most of the heavy lifting that developers will encounter and only requires that you implement Callable or Future and program to the java.util.concurrent API. IMHO it results in much more readable code and presents many fewer opportunities to incorrectly implement it due to the complexity of properly managing threads.

Upvotes: 2

Péter Török
Péter Török

Reputation: 116246

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.

Upvotes: 12

Related Questions