Ok, I'm pretty new to java programming, but I really need to pause program execution until some event happens:
while(!isItHappened());
doSomethingAfterItHappend();
What is the best way to avoid this ugly situation?
Not really dangerous (thanks to preemptive multitasking), but a waste of resources. Use a CountDownLatch with a count of 1, like startSignal in the example. Or dig deeper and implement your own waiting mechanics using Object's wait and notify / notifyAll methods.
I compared CPU usage.
CPU usage 13-15%:
while(!isItHappened());
doSomethingAfterItHappend();
CPU usage well 0-1%:
synchronized(itHappend) {
itHappened.wait();
}
doSomething();
So second piece of code is obviously better. Many thanks to duckstep.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With