pvllnspk
pvllnspk

Reputation: 5767

using synhronize for getters/setters or AtomicReference

As I understand the case like:

class Case1{
        private Object object;
        public synchronized Object getObject() {
            return object;
        }
        public synchronized void setObject(Object object) {
            this.object = object;
        }
    }

would be considered like deprecated in comparison with the:

class Case2{
    private AtomicReference<Object> object = new AtomicReference<Object>();
    public Object getObject() {
        return object.get();
    }
    public void setObject(Object object) {
        this.object.set(object);
    }
}

Am i right?

Upvotes: 2

Views: 704

Answers (2)

sjlee
sjlee

Reputation: 7876

Volatile should be sufficient. AtomicReference adds more useful operations such as getAndSet() and compareAndSet(). But if you're doing only get and set, volatile should be cheaper.

Upvotes: 1

assylias
assylias

Reputation: 328735

In both cases, the operation within the getter and the setter is atomic (reference assignment). So a more efficient (at least in terms of readability) idiom would be:

class Case3 {
    private volatile Object object = new Object();
    public Object getObject() {
        return object;
    }
    public void setObject(Object object) {
        this.object = object;
    }
}

As for your actual question, AtomicReference provides a few simple atomic operations which would make it a good choice over volatile if you need them. And synchronized makes the whole block atomic, which enables you to make even more complex operations in an atomic way.

In other words, volatile, AtomicReference and synchronized all have their specificities and are not equivalent.

Upvotes: 4

Related Questions