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

查看:192
本文介绍了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);
     }     
 }

编辑:critiquing this例子不是我的问题,我只是想知道如果数组访问一个索引,并发访问另一个索引,构成并发问题,不能想到一个简单的例子。

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天全站免登陆