Java – thread safe denies atomicboolean get() as a condition in the while loop

Suppose I have the following code:

AtomicBoolean condition;
condition = new AtomicBoolean(false);
(...)
while(!condition.get()){
   // do some stuff
}

I know condition Get () is atomic, but still! condition. Get () atom?

I mean, if a thread reads a Boolean value atomically and interrupts it before applying it, it will happen! Operation so that another thread enters the loop before? If this is the case, would it be better to use the following function:

private synchronized boolean checkNegatedCondition(AtomicBoolean cond){
    return !cond.get();
}

(...)

while(checkNegatedCondition(condition)){
   // do some stuff
}

Thank you in advance

Solution

Atomicity is not a problem

To use atoms for exclusion, you usually need atomicboolean compareAndSet(boolean,boolean).

v. Compareandset (a, b) only sets V to the value B if it is a and returns true Otherwise, if V has no value a at the beginning, it does nothing and returns false

In pseudocode, it is

synchronized public boolean compareAndSet(boolean a,boolean b){
      if(v!=a) return false;
      v=b;
      return true;
 }

But (very important) it is done atomically, so all other operations on V can be sorted before or after it

AtomicBoolean condition = new AtomicBoolean(false);
//...
if(condition.compareAndSet(false,true)){
   //Only one thread can get here unless condition is set back...
}

If you want to use it as a 'pseudo' synchronization block, you may encode:

while(!condition.compareAndSet(false,true));
   //Only one thread can get here at a time...
 condition.set(false);

This can be described as' locked ' Because the thread 'waits' to enter the controlled part, the' rotation 'is rounded in the loop until it is released This may show worse performance than synchronization because the operating system usually "pauses" waiting threads and performs other tasks However, in the case of very low contention (i.e., little or no waiting), spin locks can show better performance

Professional tip: in practice, it is best to use condition Set (false) is placed in the last block:

while(!condition.compareAndSet(false,true));
try {
   //Only one thread can get here at a time...
 }finally{
     condition.set(false);
 }

Otherwise, an exception thrown in a thread will permanently lock any access to that part of the code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>