AtomicInteger - synchronized getters / setters

Is this class thread safe?

Is it possible to see inconsistent values? Suppose that initially the value is 80. Thread 1 calls setA(100)and enters the function, but does not yet call a.set(100), and Thread 2 calls at the same time getA(). Is it possible for Thread 2 to see 80?

public class A {
    private AtomicInteger a; 

    public int getA() {
        return a.get()
    }

    public void setA(int newVal){
        a.set(newVal);
    }   
}

I know that synchronization will ensure that thread 2 sees 100, but not sure with AtomicInteger.

+5
source share
2 answers

Is this class thread safe?

Yes it is.

Thread 1 calls setA (100) and enters the function, but does not yet call a.set (100), and Thread 2 calls getA () at the same time. Is it possible for Thread 2 to see 80?

. , AtomicInteger, , 80 100.

Thread 1 AtomicInteger.set , 80 get AtomicInteger.get.

, . , get(), set(), .

.

+9

@Gray, .

get, set . Atomic* , compareAndSet - .

+1

All Articles