Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code thread safe?

I am preparing for the OCP exam and I found this question in a mock exam:

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 could you do to make this class thread safe?

And surprisingly, to me, the answer is: "Class Calculator is thread-safe"

It must be that I have not understood correctly the concept. To my understanding, a class is thread safe when all the methods work as expected under thread concurrency. Now, if two thread call at the same time getValue(), then call add() passing a different value, and then they call getValue() again, the 'second' thread won't see its value passed increased.

I understand that the oldValue and the newValue as local variables are stored in the method stack, but that doesn't prevent that the second call to compareAndSet will find that the oldValue is not the current value and so won't add the newValue.

What am I missing here?

like image 545
daniel sp Avatar asked Feb 09 '23 00:02

daniel sp


1 Answers

According to JCIP

A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.

Although there is no definition of thread-safety and no specification of the class, in my opinion, by any sane definition of an add method in a Calculator class it is "correct" if it the value of the AtomicInteger i is increased in any case, "regardless of the scheduling or interleaving of the execution".

Therefore, in my opinion, the class is not thread-safe by this definition.

like image 118
user140547 Avatar answered Feb 10 '23 13:02

user140547