简体   繁体   English

Java布尔表达式并发行为

[英]Java boolean expression concurrency behavior

Please consider the following situation. 请考虑以下情况。 There are two AtomicInteger fields in some class: 某个类中有两个AtomicInteger字段:

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 ? 例如,当我们开始对表达式求值时, firstsecond变量是否可能相等,但是在first.get()second.get()的求值之间,其中一些second.get()发生了变化,因此equal second.get() 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. 只有first.get()second.get()是原子的,每个原子都是自己的。 So the value of second can change after you've already called first.get() . 因此,在您调用first.get()之后,second的值可以更改。

You would need to synchronize or otherwise lock both first and second to assure atomicity across both. 您将需要同步或以其他方式锁定firstsecond以确保两者之间的原子性。

Can variables change values during its evaluation? 变量可以在评估过程中更改值吗?

Absolutely. 绝对。 The calls to first.get() and second.get() are made independently of each other. first.get()second.get()的调用是彼此独立进行的。 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. 如果secondfirst.get()完成之后但在second.get()开始之前发生更改, first.get()使用评估其get()时的second值。

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. 实际上,在您的场景中, firstsecondAtomicInteger ,在first == second比较中使用常规int并没有区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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