You are on page 1of 1

Thread safety and Immutability

Classes intended to be shared between threads can be made immutable, i.e., instance of the class cannot be updated (or state cannot be changed) once they are
created which ensures thread-safety. Example:

final class ImmutableValue {

private final int value;

public ImmutableValue(int value) {


this.value = value;
}

public int getValue() {


return this.value;
}

public ImmutableValue add(int val) {


return new ImmutableValue(this.value + val);
}
}

~Note: Class is made immutable above - i. the class is final ii. no setters, final member variable iii. an operation like add here, results in creating a new instance
of the class ~

Caution: The reference is NOT thread-safe

Even if the class itself is immutable and thereby thread-safe, a reference to this object may NOT be thread-safe. Example:

public class LeakyReference {

private ImmutableValue value;

public ImmutableValue getValue() {


return this.value;
}

public void setValue(ImmutableValue val) {


this.value = val;
}

public void add(int val) {


return this.value = this.value.add(val);
}
}

The class LeakyReference is not immutable even though it uses an immutable object, hence not thread-safe. It has mutator methods that can change the reference
of the instance of ImmutableValue .

== End of section ==

You might also like