Java数组线程安全 [英] java array thread-safety

查看:774
本文介绍了Java数组线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否已有一个线程从阵列的一个索引读取任何并发问题,而另一个线程写至阵列的另一指标,只要指数是不同的

Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different?

例如。 (这个例子不一定推荐真正使用,只是为了说明我的观点)

e.g. (this example not necessarily recommended for real use, only to illustrate my point)

 class Test1
 {
     static final private int N = 4096;
     final private int[] x = new int[N];
     final private AtomicInteger nwritten = new AtomicInteger(0);
     // invariant: 
     // all values x[i] where 0 <= i < nwritten.get() are immutable

     // read() is not synchronized since we want it to be fast
     int read(int index) {
         if (index >= nwritten.get())
             throw new IllegalArgumentException();
         return x[index];
     }
     // write() is synchronized to handle multiple writers
     // (using compare-and-set techniques to avoid blocking algorithms
     // is nontrivial)
     synchronized void write(int x_i) {
         int index = nwriting.get();
         if (index >= N)
             throw SomeExceptionThatIndicatesArrayIsFull();
         x[index] = x_i;
         // from this point forward, x[index] is fixed in stone
         nwriting.set(index+1);
     }     
 }

编辑:批判这个例子是不是我的问题,我真的只是想知道,如果一个指数,同时另一个索引访问数组访问,带来并发问题,也想不出简单的例子。

edit: critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.

推荐答案

虽然你提到​​你会不会改变阵列得到一个无效的状态,你将有这种情况发生时,两个线程正在查看非易失性整数没有同样的问题同步(见内存一致性错误在Java教程的部分)。基本上,这个问题是,螺纹1可以写在空间i上的价值,但也不能保证当(或如果)线程2将看到变化

While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.

java.util.concurrent.atomic.AtomicIntegerArray中做了你想做的事。

这篇关于Java数组线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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