易失性阵列的替代品 [英] alternatives for volatile array

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

问题描述

从其他问题中,我了解到volatile数组的元素不是volatile。只有引用本身是易失性的。

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.

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

在< a href =https://stackoverflow.com/questions/5173614/java-volatile-array?rq=1> 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?

推荐答案

使用 arr = arr 管理Java以重写数组的存储地址(数组也是Java中的对象)。数组字段 arr [i] 不会获得volatile属性。

Using arr=arr manages Java to rewrite the storage address of the array (arrays are also objects in Java). The array fields arr[i] do not gain the volatile property.

在某些情况下, arr = arr 可能因未知原因而起作用,但它并没有带您到安全的一面。

In some cases, arr=arr might work for unknown reasons, but it does not bring you to the safe side.

如果你想保持安全,使用 Atomic * Array 的东西。是的,额外的原子性是昂贵的,但我想如果你考虑访问时间和存储空间,它比链接结构更好。

If you want to stay safe, use the Atomic*Array stuff. Yes, the extra atomicity is costly, but I guess if you consider access times and storage footprint it is better than linked structures.

如果你想避免全局锁定,你可以考虑将数组拆分为子集。这使锁只影响一个子集,你仍然保持所有值的波动性。

If you want to avoid global locks, you may consider to split the array into subsets. This makes locks affect only a subset and you still keep the volatility for all values.

我分享你的问题,最好的选择是 Atomic * Arrays

I share your problem, by best bet are Atomic*Arrays.

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

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