I am preparing for the OCP exam, and I found this question in the exam layout:
Given:
class Calculator {
private AtomicInteger i = new AtomicInteger();
public void add(int value) {
int oldValue = i.get();
int newValue = oldValue + value;
System.out.print(i.compareAndSet(oldValue,newValue));
}
public int getValue() {
return i.get();
}
}
What can you do to make this class stream safe?
And surprisingly, for me, the answer is: "The class calculator is thread safe"
I must not have understood the correct concept. As far as I understand, a class is thread safe when all methods work as expected in a concurrency stream. Now, if two threads call getValue () at the same time, then call add (), passing a different value, and then call getValue () again, the second thread will not see that its value has passed.
, oldValue newValue , , compareAndSet , oldValue _.
?