数组在Java中是线程安全的吗? [英] Are arrays thread-safe in Java?

查看:124
本文介绍了数组在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 可以满足您的需求.

The class java.util.concurrent.atomic.AtomicIntegerArray does what you want to do.

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

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