user997112
user997112

Reputation: 30615

Most efficient Java threading technique?

There seem to be a number of different ways in which one can create threads (Runnable vs Thread class) and also ThreadPools.

Are there any difference in terms of efficiency and which are the most efficient (in terms of performance) techniques for creating and pooling threads in Java?

Upvotes: 2

Views: 950

Answers (2)

trutheality
trutheality

Reputation: 23465

At the end of the day, they're all relying on the same underlying Thread-based mechanism to actually do the work. That means that if you are asking "what is the most efficient way to start a single thread?" the answer is, create a Thread object and call start() on it, because any other method will take some other steps before it eventually creates a Thread object and calls start() on it.

That doesn't mean that this is the best way to spawn threads, it just means that it is the most low-level way to do it from Java code. What the other ways to create threads give you is different types of infrastructure to manage the underlying Threads, so your choice of method should depend on the amount and kind of infrastructure you need.

Upvotes: 0

dash1e
dash1e

Reputation: 7807

If you need to handle many short and frequent requests it is better to use a ThreadPool so you can reuse threads already open and assign them Runnable tasks.

But when you need to launch a thread for a single task operation or instantiate a daemon thread that run for all the application time or for a long specific time then could be better create a single thread and terminate it when you don't need it anymore.

Upvotes: 3

Related Questions