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.