简体   繁体   中英

Reasons for not using Thread.join()

Lately, I have been told by Senior Developers not to use Thread.join() to wait for another Thread to finish. I've also seen several such questions on SO asking alternates to join.

In my research, I couldn't find anything wrong with join(). In fact it is widely used.

So I would like to know why not use join()? What is wrong with it? Does it promotes poor programming or architecture?

There's nothing wrong with join() . It is as good as it gets.

However, here's why you shouldn't architect your application to rely on joins. In Java, the primary abstraction for running tasks isn't Thread anymore. It is Executor . That is you wrap the concurrent tasks as Callable and simply submit it to an Executor without worrying about the execution details. This is how Executor s work. You submit or execute a Callable or Runnable respectively and no need to specify Thread.

So I would like to know why not use join()?

Then here's your reason: Since you don't create or manipulate Threads in the Executor world, there's no point in using join . Almost every join could be replaced with something else ( Future.get , CountDownLatch , Locks , etc.).


Note: I'm not saying that you don't need to manipulate Threads when using Executors. In some cases, it's better to create own Thread subclass and then have Executor use them via ThreadFactory .

There's nothing wrong with using Thread.join in general, however you need to be very careful and know where the thread comes from . If it comes from a thread pool - then you're in a trouble indeed, because such threads are running until the pool is terminated and shared between several workers.

IMO there is nothing wrong with join. You just need to take care to ensure that the thread you are waiting on terminates in all circumstances. Since if it does not then the execution may halt forever. So if you are making the main thread wait on some thread using join and the thread does not terminate it may cause your entire application to freeze.

A Fork/Join framework was introduced in Java 7. Consider using it instead of Thread.join(). In general you should use classes from package java.util.concurrent.* where possible, minimizing usage of original synchronization techniques like synchronized blocks, wait/notify and join. java.util.concurrent gives much more flexibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM