简体   繁体   中英

Java boolean expression concurrency behavior

Please consider the following situation. There are two AtomicInteger fields in some class:

private final AtomicInteger first = new AtomicInteger();
private final AtomicInteger second = new AtomicInteger();

Then I have something like this:

boolean equal = first.get() == second.get();

So the question is how exactly this expression is evaluated? Can variables change values during its evaluation? For example is it possible that both first and second variables are equal when we start to evaluate the expression, but between evaluation of first.get() and second.get() some of them changes so equal evaluates to false ? Or the expression is evaluated atomically by comparing snapshots of the variables on invocation?

Thanks in advance!

You're assuming correctly. Only first.get() and second.get() are atomic, each on it's own. So the value of second can change after you've already called first.get() .

You would need to synchronize or otherwise lock both first and second to assure atomicity across both.

Can variables change values during its evaluation?

Absolutely. The calls to first.get() and second.get() are made independently of each other. If second changes after first.get() is completed but before second.get() is started, the value of second as of the time of evaluating its get() would be used.

In fact, in your scenario there is no difference between first and second being AtomicInteger s and using regular int s in first == second comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM