1

I know that CountDownLatch is used to synchronize between processing in multiple threads. But my question is about using CountDownLatch for something it is not especially used for: waiting for some time before continuing executing instructions in the same thread.

//the countDown instance is not shared with any other thread
CountDownLatch countDown = new CountDownLatch(1);
try {
    //here I just want to "sleep" for one second
    countDown.await(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
    //handle exception
}

Obviously here, the await will only return after 1 second (nobody is countdowning the CountDownLatch). I want to know if there is a difference between using this approach and simply using Thread.sleep, especially regarding CPU usage.

Even if the CountDownLatch instance is not shared between threads, the code snippet above is used in a context where multiple threads are running this code (so, each with its own CountDownLatch that is used only for the purpose of sleeping).

A colleague of mine is stating that it is more (CPU) efficient to use countDownLatch.await(timeout), but I'm puzzled about the reasons. If there are any reason (for any particular context) where such usage is more efficient than Thread.sleep, I want to know about it and about the reasons.

Thanks in advance.

Hamdi Douss
  • 1,033
  • 1
  • 8
  • 17
  • 3
    Your colleague is wrong. And regardless, it’s a sleeping operation, so who cares about efficiency? The whole point is to do nothing for a specific period of time. – VGR Oct 23 '19 at 20:03
  • 1
    "but I'm puzzled about the reasons" did s/he explain the reasons? If so, what were they? – Andy Turner Oct 23 '19 at 20:10
  • Not really, I don't have daily exchange with him. He does not really know the reasons. Anyway, It is not the most important part of the question. – Hamdi Douss Oct 25 '19 at 08:22
  • If he/she/it/whatever doesn't know why, there is nothing to discuss. No reason to even ask anybody else, only the source of the disinformation. – user207421 Oct 25 '19 at 08:44

0 Answers0