Esistono problemi di concorrenza con una lettura thread da un indice di un array, mentre un altro thread scrive su un altro indice dell'array, purché gli indici siano diversi?java array thread-safety
ad es. (Questo esempio non necessariamente raccomandato per l'uso vero e proprio, ma solo per illustrare il mio punto)
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: criticare questo esempio non è la mia domanda, io letteralmente voglio solo sapere se l'accesso array per un indice, in concomitanza a l'accesso a un altro indice, pone problemi di concorrenza, non potrebbe pensare ad un semplice esempio.
grazie ... drat, volevo usare un array byte [] e sembra che non ci sia un tale animale atomico .... Immagino che userò solo i metodi sincronizzati e lo terrò semplice. –
Se hai molte più letture rispetto alle scritture potresti voler guardare java.util.concurrent.locks.ReadWriteLock –
huh, interessante ... –