Mohammed Falha
Mohammed Falha

Reputation: 967

increase Thread start performance in java

Is there a way to increase the performance of Thread.start method. as i know Thread.start will call the run method of the tread in a separate thread but i have found that it need time more than simple method call in the calling context.

Upvotes: 5

Views: 3625

Answers (4)

Vaibhav Raj
Vaibhav Raj

Reputation: 2232

Thread creation always takes time. The traditional approach

new Thread(runnableObj).start();

creates new Thread everytime we call start() method.

Use Executors, if you don't want to spend extra time in creating threads while your business logic is being run. You can configure and create Thread Pools when your application starts.

Here is a good short tutorial for Executors

Upvotes: 2

Narendra Pathai
Narendra Pathai

Reputation: 42005

Starting threads, context switching and destroying threads all require precious CPU cycles. So it is best to use Thread Pooling which suits your requirement.

There are various options available:

  • Cached Thread Pool - caches some threads to improve performance

  • Single Thread pool executor - A single thread executor

  • Fixed Thread Pool executor - An executor with fixed size

Switching can be reduced by creating n threads based on your hardware configuration and other parameters.

Advantage of executors over Thread.start():

  • Re use of existing threads, so threads are not created every time a task is submitted
  • Thread management is done by executors

Upvotes: 2

selig
selig

Reputation: 4844

Thread.start is native. It does a lot more than calling run - it uses Operating System calls to create a thread stack and lots of other things. Consider using a Thread Pool.

Upvotes: 2

pamphlet
pamphlet

Reputation: 2104

Starting threads definitely involves overhead. You may want to consider thread pooling.

http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html

Upvotes: 7

Related Questions