Stavo usando AtomicReference per implementare AtomicInteger. Tuttavia, durante i test, ho notato che anche in un singolo thread l'operazione CAS si è bloccata una volta che il suo valore ha raggiunto 128 .. Sto facendo qualcosa di sbagliato o c'è un avvertimento in AtomicReference (potrebbe essere correlato alla CPU)? Qui è il mio codice:Perché il CAS AtomicReference restituisce false con il valore 128?
public class MyAtomInt {
private final AtomicReference<Integer> ref;
public MyAtomInt(int init) {
ref = new AtomicReference<Integer>(init);
}
public MyAtomInt() {
this(0);
}
public void inc() {
while (true) {
int oldVal = ref.get();
int nextVal = oldVal + 1;
boolean success = ref.compareAndSet(oldVal, nextVal); // false once oldVal = 128
if (success) {
return;
}
}
}
public int get() {
return ref.get();
}
static class Task implements Runnable {
private final MyAtomInt myAtomInt;
private final int incCount;
public Task(MyAtomInt myAtomInt, int cnt) {
this.myAtomInt = myAtomInt;
this.incCount = cnt;
}
@Override
public void run() {
for (int i = 0; i < incCount; ++i) {
myAtomInt.inc();
}
}
}
public static void main(String[] args) throws Exception {
MyAtomInt myAtomInt = new MyAtomInt();
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.submit(new Task(new MyAtomInt(), 150)).get();
System.out.println(myAtomInt.get());
exec.shutdown();
}
}
Perché stai cercando di implementare il tuo 'AtomicInteger' quando JDK lo fornisce? Sei su una piattaforma in cui non è supportato o è un esercizio? – Axel
Questa è solo una pratica per familiarizzare con il pacchetto java.util.concurrent.atomic, e sì sicuramente non abbiamo bisogno di reinventare le ruote :) – Alan