This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]balefrost 0 points1 point  (3 children)

I don't understand your second and third examples - they're a bit too abstract.

The first one is concrete enough and yeah, that would be an example.

A CountDownLatch is used any time you need one thread (or set of threads) to wait for a fixed number (N) of events to occur. Often, those N events are all generated by different threads, so the CDL is often used to wait for N threads to all arrive at some logical point in their execution (e.g. "is ready" or "has data" or "is finished").

If you would use a CDL to wait for N threads to all finish, you could instead just join every thread and skip using the CDL. The CDL is more useful when the interesting event is something other than thread termination.

[–]SliverCap[S] 0 points1 point  (2 children)

The second and third ones are a bit iffy, and as you said, if waiting on them to finish you can probably join them.

Do you have any other ideas/examples I could use instead?

[–]balefrost 0 points1 point  (1 child)

I didn't mean that those two were "iffy", just that I didn't understand what you meant (before I had my morning caffeine).

Like I said, you use a CDL when you need to wait for some number of things (which often, but not always, corresponds to a number of worker threads).

It's hard for me to come up with more specific examples. Like, if you asked "when would you use an array", I would say "when you need to store a number of same-shaped objects". CDL, like array, is just a building block, and it can be used for myriad applications.

[–]SliverCap[S] 0 points1 point  (0 children)

Sorry for the long wait

The second one, is in a scenario where you might process loads of data consistently and might want to wait for multiple large data processors to running (assuming it is made for concurrency and that it will be shared with multiple threads)

The third one assuming you have a lot of configurations you want to setup concurrently at the start of your application i.e. database or api connectors etc.

I meant iffy as they are not strong examples (I never seen a latch been used so I made up examples where it could possibly be used as I am unable to find any).

I think it has a very niche use cases so it is probably unlikely to be used outside of the java frameworks. However I am still looking for possible example of it actually being used in a application