Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New threads vs. reusing threads

We have a desktop application that has some background threads and, because of execution of external commands, also needs threads for handling the out and err streams.

We could either create new threads and let them finish or we could reuse threads. Would reusing threads have some benefit, e.g. in case of performance or memory usage?

like image 497
Thomas S. Avatar asked Dec 19 '22 13:12

Thomas S.


1 Answers

There is no way to reuse a Thread because Thread once finishes (exit the run() method) its Thread.State passes from Thread.State.RUNNABLE to Thread.State.TERMINATED and the Thread class does not have a setState(Thread.State) method for setting its state to reuse it.

However we can take help of Thread Pooling in Java. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

Advantage of Thread Pooling :

  1. Thread pooling saves the virtual machine the work of creating brand new threads for every short-lived task.
  2. It minimizes overhead associated with getting a thread started and cleaning it up after it dies
  3. By creating a pool of threads, a single thread from the pool can be recycled over and over for different tasks.
  4. Reduce response time because a thread is already constructed and started and is simply waiting for its next task
like image 175
SparkOn Avatar answered Jan 06 '23 17:01

SparkOn