Wait until the boolean value changes.

I have a thread that is waiting for a boolean to change as follows:

while(!value) { Thread.sleep(1000) } // Do some work after change of the value 

This is not my preferred way of doing this, causing massive CPU consumption.

Is there a way to block Thread until the boolean value changes?

+30
java multithreading boolean
Sep 26 '13 at 10:11
source share
5 answers

This is not my preferred way of doing this, causing massive CPU consumption.

If this is really your working code, just save it like that. Checking the logical value once per second causes a lack of measurable CPU load. Nothing.

The real problem is that the thread that checks the value may not see the changes that have occurred over an arbitrarily long time due to caching. To ensure that the value is always synchronized between threads, you need to put the volatile keyword in the variable definition, i.e.

 private volatile boolean value; 

Note that including access in a synchronized block, for example, when using the notification solution described in other answers, will have the same effect.

+54
Sep 26 '13 at 10:23
source share

You need a mechanism that avoids lively waiting. The old wait/notify fraught with traps, so prefer something from the java.util.concurrent library, such as CountDownLatch :

 public final CountDownLatch latch = new CountDownLatch(1); public void run () { latch.await(); ... } 

And then call

 yourRunnableObj.latch.countDown(); 

However, starting a thread to do nothing, but waiting until it is needed is still not the best way. You can also use the ExecutorService , to which you submit as a task the work that must be performed when the condition is met.

+34
Sep 26 '13 at 10:22
source share

How about wait-notify

 private Boolean bool = true; private final Object lock = new Object(); private Boolean getChange(){ synchronized(lock){ while (bool) { bool.wait(); } } return bool; } public void setChange(){ synchronized(lock){ bool = false; bool.notify(); } } 
+6
Sep 26 '13 at 10:16
source share

Well, maybe this should solve your problem. Note that each time you make changes, you call the change () method, which frees the wait.

 Integer any = new Integer(0); public synchronized boolean waitTillChange() { any.wait(); return true; } public synchronized void change() { any.notify(); } 
+2
Sep 26 '13 at 10:30
source share

I prefer to use the mutex mechanism in such cases, but if you really want to use boolean, then you should declare it mutable (to ensure that changes are visible across the threads) and just start the loop without taking the body into account with such a logical value as the condition:

 //.....some class volatile boolean someBoolean; Thread someThread = new Thread() { @Override public void run() { //some actions while (!someBoolean); //wait for condition //some actions } }; 
+1
Sep 26 '13 at 10:25
source share



All Articles