MAG
MAG

Reputation: 474

creating and killing a thread vs using .notify () and .wait ()

Assuming a control thread has access to a bunch of threads and to the objects this thread would wait on. Which one will have a greater impact in performance if I have to start and stop, what several of these threads are doing, from this single control thread ?

Wouldn't it just be better for example to kill it via interruption and just create a new one with the same Runnable?

Upvotes: 0

Views: 302

Answers (2)

Stephen C
Stephen C

Reputation: 719336

Creating (actually start()-ing) a new thread is relatively expensive, so from a performance perspective it would be better to use wait / notify.

Secondly, interrupt is not guaranteed to "stop" a thread. The thread may choose to ignore the interrupt ... or if it is purely CPU bound, it may not notice it at all.

There is also a third option: use an existing thread pool mechanism. For example, the ExecutorService API has a various implementations that provided bounded and unbounded thread pools. These can take care of scaling up and down, and pool shutdown. You use them by submit(...)-ing tasks as Runnable instances and you optionally get a Future that allows you to wait for the task completion.

Finally, for most concurrent programming use-cases, there are standard classes that support the use-case, and it is better to use them rather than attempting to implement from scratch; e.g. using wait / notify directly. In your case, you probably need some kind of "barrier" mechanism: java.util.concurrent.Phaser might be the one that you need.

Upvotes: 1

ventsyv
ventsyv

Reputation: 3532

Threads are fairly independent from one another and in most cases each thread will know better than the control thread when it's ready to terminate. Killing a thread is very abrupt thing, it's much better to wait for the threat to terminate itself cleanly.

Upvotes: 0

Related Questions