java 线程数组,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.

解决方案

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值