Difference between wait-notify and CountDownLatch

I need help understanding the benefits of using CountDownLatch over traditional wait notification. I think that notifyAll () really does the same, and it seems more convenient to use (perhaps due to dating).

Also, what is the difference between wait () and wait () from CountDownLatch?

Thanks!

EDIT: I think I need to rephrase my queries:

Waiting () according to documents:

Causes the current thread to wait until the latch goes down to zero if the thread is not interrupted.

It's hard for me to understand the difference between wait () and wait () - await () actually uses wait () under the covers, and it seems that there is an implicit notifyAll () when the number has reached zero.

I wanted to ask why I should not just use the wait-notifyAll () mechanism (with my own processing of the counting variable), and not for CountDownLatch?

+6
source share
1 answer

They, of course, do not do the same: CountDownLatch only signals when the event counter reaches 0, and it does it automatically, wait-notify requires that you save your own account if you want to achieve the same behavior. Implementing the same behavior is often error prone, and this is best avoided (especially if you are new to concurrency programming). Comparing CountDownLatch and wait-notify is hardly even a comparison of apples with oranges, it is more like comparing an Allen automatic drill and a wrench.

I don’t know if you used notifyAll() and CountDownLatch , but only notifyAll() will not give you the same behavior if you did not count how many events happened. CountDownLatch is probably best suited for a fixed number of tasks and waiting for those tasks to complete before you resume the rest of your program. This is especially useful when you have a fixed number of threads (e.g. ThreadPool ) that perform a fixed number of tasks, but your threads are much smaller than tasks, and you should reuse them. With CountDownLatch you can easily wait for all tasks to complete. I don’t know how you used notifyAll() to achieve the same behavior, but if you provide us with more information, we can decide which of the two options is the best choice (there are, of course, some cases where waitNotify() more suitable) .

Regarding the difference between wait() and await() , I'm somewhat disappointed with you! Finding a document is the first step to any question:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

await() is the actual function of CountDownLatch , while wait() inherited from Object . I would recommend that you check the documentation for what they do.

+9
source

Source: https://habr.com/ru/post/915748/


All Articles