爪哇 - 替代品挥发阵列 [英] java - alternatives for volatile array

查看:127
本文介绍了爪哇 - 替代品挥发阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从其他的问题,我了解到,挥发性数组的元素不挥发。只有引用本身就是不稳定。

From other questions, I learned that the elements of a volatile array are not volatile. Only the reference itself is volatile.

volatile[] int data;

Thread A: data[4] = 457;
Thread B: System.out.println(data[4]);

下面,线程B可能永远不会看到更新后的值。

Here, Thread B might never see the updated value.

哪些选项/替代我必须做到同样的事情?我想,以避免对阵列进行同步,因为它几乎不改变。但是,它是由一些线程读了很多。同步它很可能降低的吞吐量,这是在本实施例中很重要的。

Which options/alternatives do I have to achieve the same thing? I would like to avoid having to synchronize the array, since it is hardly ever altered. However, it is being read a lot by some threads. Synchronizing it will very likely lower the throughput, which is very important in this example.

是我唯一的选择一个写入时复制的数据结构在这里?也就是说,事后阵列复制到一个新的数组并更新数组引用。

Is my only option a copy-on-write data-structure here? That is, copying the array into a new array and update the array reference afterwards.

是否还有其他选择吗?我读的地方,数组封装到一个类(只有一个成员,数组)达到同样的事情,但我怀疑这是真的。我看不出怎么可能帮助。

Are there any other options? I read somewhere that encapsulating the array into a class (with only one member, the array) achieves the same thing, but I doubt that is true. I cannot see how that might help.

请注意,我的目标是JVM 1.4。这意味着我不能使用的java.util.concurrent 包。

Please note that my target JVM is 1.4. This means I cannot use the java.util.concurrent package.

--------------编辑编辑编辑--------------

的Java数组波动?中,我读了重新分配数组引用实现波动性语义。这应该给正确的结果:

In Java volatile array? I read that re-assigning the array reference achieves the volatility semantics. This should give the correct results:

volatile[] int data;

Thread A: data[4] = 457;
Thread A: data = data;
Thread B: System.out.println(data[4]);

是较旧的JVM这有效吗?

Is this valid on older JVMs?

推荐答案

只需使用包装:

class VolatileInt{
    volatile int value;
}

VolatileInt[] create(int size){
    VolatileInt[] array = new VolatileInt[size];
    for(int k=0;k<size;k++)
        array[k]=new VolatileInt();
    return array; 
}

VolatileInt[] array = create(10);

这篇关于爪哇 - 替代品挥发阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆