Why is this code stream safe?

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 _.

?

+4
4

JCIP

, ,       .

, , , add Calculator , AtomicInteger i " ".

, , .

+3

"", . , , , . .

JLS :

, .

,

- , , i happens-before , , .

, / , - , ( , ).

+3

add :

  • value i true.
  • false.

1 , , :

, , .

, , , , .

, , add value i, . , . ( add , add ... , , . )


1. , (. 2016-01-17) : " , , ". , , " ". Eric Lippert 2009 " , ?" , .

+2

, compareAndSet , .

It does not matter how many threads the method body enters at the same time. The first, which reaches the end, and calls compareAndSet “wins” and gets to change the value, while others find that the value has changed on them, and compareAndSet returns false. This never leads to the system being in an undefined state, although callers may have to handle the false result in any realistic scenario.

0
source

Source: https://habr.com/ru/post/1624617/


All Articles