인덱스가 다른 한 스레드가 배열의 다른 인덱스에 쓰는 동안 배열의 한 인덱스에서 읽는 스레드에 동시성 문제가 있습니까?java 배열 스레드 안전
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);
}
}
편집 (이 예는 반드시 단지 내 지점을 설명하기 위해 실제 사용하지 않는 것이 좋습니다) :이 예제를 비판 내 질문없는, 말 그대로 단지 동시에, 하나 개의 인덱스에 경우 배열 액세스를 알고 싶어요 다른 색인의 액세스, 동시성 문제 제기, 간단한 예제를 생각할 수 없었다.
감사합니다 ... drat, byte 배열을 사용하고 싶었습니다. .... 나는 그냥 동기화 된 메서드를 사용하고 간단하게 유지할 것입니다. –
쓰기보다 읽기가 더 많은 경우 java.util.concurrent.locks.ReadWriteLock을 참조하십시오. –
흥미 롭습니다 ... –