Reputation:
I have a small question about Java AtomicInteger
.
I know that I can realise thread-safe counters. But I couldn't find anything about complex calculations with AtomicInteger
.
For example I have this calculation (i and j are object-vars, "this"):
public void test(int x) {
i = i + ( j * 3 ) + x
}
Is it possible to make this method thread-safe only with AtomicInteger
?
Is this valid?
public void test(int x) {
do {
int tempi = i.get();
int tempj = j.get();
int calc = tempi + ( tempj * 3 ) + x;
} while (i.compareAndSet(tempi, calc));
}
I think not because a thread could change j while the calculation.
To avoid this I have to control if j is changed while the calculation. But I don't find a "just compare" function in AtomicInteger
.
Pseudocode:
public void test(int x) {
do {
int tempi = i.get();
int tempj = j.get();
int calc = tempi + ( tempj * 3 ) + x;
} while (i.compareAndSet(tempi, calc) && j.compare(tempj) /* changed */);
}
Can anybody help me to clarification?
Upvotes: 1
Views: 241
Reputation: 44952
Since your calculations operate on multiple AtomicXXX
objects (i
, j
) they are not thread-safe. AtomicXXX
semantics are implemented with Compare-and-Swap (CAS) instructions that do not support more than one placeholder at a time. You need an external monitor lock to make it thread-safe.
Upvotes: 3