super.t
super.t

Reputation: 2746

Volatile for publishing effectively immutable objects

Would it be safe to use only volatile for publishing a mutable object which is never mutated?

class Mutable {

private int i;

Mutable(int i) {
 this.i=i;
}

int getI() {
 return i;
}

}

This class is accessed by multiple threads:


@Singleton
class Holder {

private volatile Mutable effectivelyImmutable = new Mutable(1);

int getI() {
 return effectivelyImmutable.getI();
}

void resetMutalbe(int i) {
 Mutable newMutable = new Mutable(i);
 effectivelyImmutable = newMutable;
}

}

Would all threads get 1 from Holder.getI() if Holder.resetMutalbe() is never called?

Would all threads get 2 from Holder.getI() if Holder.resetMutalbe(2) was called from any thread before Holder.getI()?

Upvotes: 0

Views: 91

Answers (1)

user3453226
user3453226

Reputation:

Yes, volatile is enough, since it creates a happens-before relationship. Writes to a volatile field happen-before reads to it, so all actions prior to calling Holder#resetMutalbe() are visible after calling Holder#getI().

Upvotes: 1

Related Questions