deinocheirus
deinocheirus

Reputation: 1863

Thread-safety idiom for getters in a Java class other than "synchronized"

public class ThreadSafe {

    private int aField;

    public synchronized void setAField(int value) {
        aField = value;
    }

    public synchronized int getAField() {
        return aField;
    }

}

public class ThreadSafeToo {

    private volatile int aField;

    public synchronized void setAField(int value) {
        aField = value;
    }

    public int getAField() {
        return aField;
    }

}

public class DontKnowIfThreadSafeButMostLikelyYes {

    private static int aField;

    public synchronized void setAField(int value) {
        aField = value;
    }

    public int getAField() {
        return aField;
    }

}

Questions:

Upvotes: 1

Views: 139

Answers (4)

assylias
assylias

Reputation: 328737

ThreadSafeToo does not need a synchronized method: volatile assignment is atomic and provides visibility guarantees.

DontKnowIfThreadSafeButMostLikelyYes is not thread safe: you need to synchronize reads AND writes to shared variables.

Preferred idiom is subjective, but in your case, the efficient approach is:

public class ThreadSafeToo {
    private volatile int aField;
    public void setAField(int value) { aField = value; }
    public int getAField() { return aField; }
}

Upvotes: 5

Ankit
Ankit

Reputation: 6622

Is DontKnowIfThreadSafeButMostLikelyYes thread-safe?

No, because when getter & setter are being called the same moment getter might return old value.

What would be the preferred idiom and why?

In this case the 2nd class is correctly synchronized & is thread safe

Upvotes: 0

maxammann
maxammann

Reputation: 1048

As far as I know DontKnowIfThreadSafeButMostLikelyYes is not thread-safe, because 2 threads could set and get aField at the same moment -> problem

There is no difference if you put the static or not. Both would be not thread-safe.

I think there is no real preferred idom. In this case I would choose the first way. But you can also use the second one or you could use locks.

Upvotes: 0

Uwe Plonus
Uwe Plonus

Reputation: 9954

Your class DontKnowIfThreadSafeButMostLikelyYes is not thread safe because a static variable is not different from an instance variable from point of synchronization. Besides this the result will not be the same as in the other cases.

Also the second question is opinion based.

Upvotes: 0

Related Questions