Same condition logic generating two very different byte codes for AtomicBooleans in Java. Why?

StackOverflow https://stackoverflow.com/questions/21925839

سؤال

If I do this, my program works very fine:

if (atomicBoolean1.get() == false && atomicBoolean2.get() == true 
     && !atomicBoolean1.compareAndSet(false, true)) {

    continue;
}

Now if I do this, everything breaks:

if (atomicBoolean1.get() == false && atomicBoolean2.get() == true) {

    continue;
}

if (!atomicBoolean1.compareAndSet(false, true)) {

    continue;
}

Am I getting insane?

هل كانت مفيدة؟

المحلول

continue jumps to the next iteration.

They both are not same. Same should be

if (atomicBoolean1.get() == false && atomicBoolean2.get() == true) {   
  if (!atomicBoolean1.compareAndSet(false, true)) {
      continue;
  }
}

نصائح أخرى

Actually you are not doing exactly similar things in above 2 cases.

In case1,

atomicBoolean1.get() == false && atomicBoolean2.get() == true 

if above 2 conditions satisfied only,

atomicBoolean1.compareAndSet(false, true)

function is calling.

But in case2,

atomicBoolean1.get() == false && atomicBoolean2.get() == true 

if above 2 conditions satisfied, it will go back to loop start. so will not call

atomicBoolean1.compareAndSet(false, true)

If those 2 conditions failed only, it will call

atomicBoolean1.compareAndSet(false, true)

I think, I may cause any problem.

Lets give more details about your program and what you are trying to do. It may help to figure out the issue.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top