Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it dangerous to use while to pause the entire java program?

Tags:

java

loops

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?

like image 961
J. Leeroy Avatar asked Aug 24 '26 09:08

J. Leeroy


2 Answers

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.

like image 178
duckstep Avatar answered Aug 26 '26 21:08

duckstep


I compared CPU usage.

  1. CPU usage 13-15%:

    while(!isItHappened());
    doSomethingAfterItHappend();
    
  2. CPU usage well 0-1%:

    synchronized(itHappend) {
        itHappened.wait();   
    }
    doSomething();
    

So second piece of code is obviously better. Many thanks to duckstep.

like image 44
J. Leeroy Avatar answered Aug 26 '26 22:08

J. Leeroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!