简体   繁体   English

在java中返回一个原子操作的int?

[英]Is returning an int an atomic operation in java?

// is this atomic? 
public int size() {
    return count;
}

Note that count can be changed by other methods in other threads. 请注意,可以通过其他线程中的其他方法更改计数。

I know integer reads and writes are atomic, but I am not sure about return. 我知道整数读取和写入是原子的,但我不确定返回。

What got me alarmed is that for some reason ArrayBlockingQueue locks it's size() method. 令我惊慌的是,由于某种原因, ArrayBlockingQueue锁定了它的size()方法。

Reads and writes to primitive int are atomic as you already know. 您已经知道,对原始int读取和写入是原子的。 Returning is basically reading and placing in some other place in memory. 返回基本上是读取并放置在内存中的其他位置。 Since reading is atomic, no race condition will occur. 由于读数是原子的,因此不会出现竞争条件。 You either return previous or next value of int . 您可以返回int上一个或下一个值。

Using lock in ArrayBlockingQueue might be due to visibility reasons. ArrayBlockingQueue使用lock可能是由于可见性原因。 count variable is not volatile so if the queue was modified in the meantime, without some sort of locking you are not guaranteed to see the most recent value of count . count变量不是volatile所以如果在此期间修改了队列,没有某种锁定,你不能保证看到最新count值。 But since read and writes are atomic, at least you'll never see youngest 16 bits of old value and oldest 16 bits of new value. 但由于读写是原子的,至少你永远不会看到最新的16位旧值和最新的16位新值。

Reading primitives ( except long and double) is atomic. 读取原语(long和double除外)是原子的。

But suppose there is a synchronized method which is modifying value of the count ; 但是假设有一个同步方法正在修改计数的值; in such case your read may or may not be atomic. 在这种情况下,您的阅读可能是也可能不是原子的。

 synchronized void changeCount(){
     //modifying value of count
 }

So in that case you should also synchronized your read method or minimum declare count as volatile. 因此,在这种情况下,您还应将读取方法或最小声明计数同步为volatile。 This will ensure that read is also atomic and the correct and consistent value is returned 这将确保读取也是原子的,并返回正确且一致的

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

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