Re: Atomic integer array class question
On 1/9/2012 8:17 AM, raphfrk@gmail.com wrote:
On Jan 9, 3:45 pm, Knute Johnson<nos...@knutejohnson.com> wrote:
Read the package description for java.util.concurrent.atomic to get a
good idea of what the Atomic variables are. But no the performance will
not be as good as a regular array.
Sorry, I wasn't clear, I didn't mean compared to a regular array.
AtomicIntegerArray intArray = new AtomicIntegerArray(10);
compared to
AtomicInteger[] intArray = new AtomicInteger[10];
If 2 writes happen to an AtomicIntegerArray, but at different
locations, do they interfere?
Why don't you post something about what you are really going to do with
the array and maybe somebody can give you a better idea of what way to go.
I was wondering if having writes to an array happen one at a time
would be slower than an AtomicIntegerArray.
I don't understand this comment. Each AtomicIntegerArray operation
refers to a specific element, so writes must happen one at a time anyway.
Something like (though not actually for int arrays, as then I would
just use AtomicIntegerArray)
private final int UNSTABLE = 0;
int[] array = new int[1000];
AtomicInteger sequence = new AtomicInteger(1);
public void set(int index, int value) {
while (true) {
int oldSequence = sequence.getAndSet(UNSTABLE);
if (oldSequence == UNSTABLE) {
continue;
}
Spin waiting, especially spin waiting that has no delay and includes
access to a volatile variable, can be very expensive in terms of load on
the processor-memory interconnect.
I would do some benchmarking, but are you sure this is better than
synchronization?
array[index] = value;
sequence.set(oldSequence + 2);
return;
}
}
public void get(int index) {
while (true) {
int initialSequence = sequence.get();
if (localSequence == UNSTABLE) {
continue;
}
int value = array[index];
int finalSequence = sequence.get();
if (initialSequence != finalSequence) {
continue;
}
return value;
}
}
So, the effect is that writes happen one at a time. If a thread sets
the sequence number to UNSTABLE, then all other writers will
spinlock. Also, if any element is changed, then all readers will
detect it and have to retry (even though their data was actually not
changed).
I'm still unclear what is intent, and what is infrastructure to do with
how you are trying to implement the intent. Could you provide a
description of what you want to have happen?
Patricia