2

参考地点。http://en.wikipedia.org/wiki/Locality_of_reference。所以它就像迭代一个小的int数组会比迭代一个linkedList更快。因为数组是连续的,并且所有数组都可以放入 cpu 缓存中,并且缓存未命中率会更少。

但我想要一个简单的 int 数组和一个 volatile 数组之间的比较。AFAIK 迭代易失性数组将导致每次读取易失性,这可能在某些系统中导致每次读取时更新缓存。

int[] arr; // assume here i have declared and initialized it.
int sum = 0;
for(int i=0;i<arr.length;i++){
    sum = sum + arr[i];
}

挥发性对应部分

volatile int[] arr; // assume here i have declared and initialized it.
int sum = 0;
for(int i=0;i<arr.length;i++){
    sum = sum + arr[i]; // volatile read everytime
}

那么它们是否相同,或者编译器会将所有易失性读取变成单个易失性读取(编译器优化)

4

2 回答 2

3

如果您需要对数组进行易失性访问,可以使用AtomicIntegerArray。这包装了一个int数组,但提供了线程安全的语义。

AtomicIntegerArray array = new AtomicIntegerArray(100);
array.addAndGet(1);
array.lazySet(10, 123);
int n = array.get(5); // volatile get
array.set(9, 333); // volatile set.
于 2013-10-21T17:08:51.873 回答
0

Just a slight improvement to Scientist's code: You don't actually need an additional volatile boolean flag, you can get by with just the following:

volatile int[] array = ...;

void write(int index, int value){
    array[index]=value;
    array = array; // explicit volatile write
}

int read(int index){
    return array[index]; // implicit volatile read
}

The major change is that you don't need an additional read of a volatile variable for the read, since accessing the ith element of an array involves reading the volatile reference to the array (whether the JIT/compiler actually does is a different thing, but it has to give you the same guarantees). So that's quite nice as it's exactly the code you'd write anyhow. Sadly that doesn't work for writes to the array so you have to do this really ugly self-assignment.

That said the AtomicIntegerArray class is just as efficient (you'd hope so at least) as this and makes the whole thing explicit.

于 2013-10-22T00:53:48.803 回答