multithreading - What's the point of CountDownLatch in java? -


this question has answer here:

countdownlatch in java high-level synchronization utility used prevent particular thread start processing until threads ready.

but, semaphore can totally same thing. so, what's merit of countdownlatch?

one more question: if countdownlatch have merits, why designed used once? think it's easy add set method reset count.

semantically, they're different; , matters, because makes code easier read. when see semaphore, start thinking "a limited amount of shared resource." when see countdownlatch, start thinking "a bunch of threads waiting 'go!' signal." if give me former in code needs latter, it's confusing.

in sense, semaphore being used countdownlatch bit garden-path sentence; while technically correct, leads people astray , confuses them.

in terms of more pragmatic uses, countdownlatch simpler if that's need. simpler better!

as reusing countdownlatch, complicate usage. instance, let's you're trying queue threads a, b, , c work. have them await on latch, , release it. reset it, presumably queue threads d, e , f other work. happens if (due race condition), thread b hasn't been released first latch yet? if hadn't gotten await() call yet? close gate on it, , tell wait d, e , f second opening? might cause deadlock, if second opening depends on work b supposed doing!

i had same questions did resetting when first read countdownlatch. in practice, i've wanted reset one; each unit of "wait go" (a-b-c, d-e-f) naturally lends creating own countdownlatch go along it, , things stay nice , simple.


Comments