Friday, 20 May 2011

Thread-Safe Immutable Objects

Threading problems are the most weird and difficult bugs to fix, mainly because they’re so hard to reproduce. You can mitigate some of these problem by designing thread-safe code, which isn’t so hard as you think.

The code below is an example of a thread-safe technique that's for synchronising the update of instance variables without the need for language specific locking and mutexes. The big idea is that we tie two or more instance variables together in a bean. The fields are final and obey the Java rules of only being updated table during either static initialisation or when the constructor is called.

In a production environment, it would be a good idea to implement equals() and hash() for these kinds of object, together with a copy constructor.

Each time there is a need to change one of the instance values, you need to construct a new object, which may seem messy, but the values of the attributes are guaranteed no matter how many threads are simultaneously accessing the object.

public class ImmutableBean {

private final int var1;
private final String var2;
private final String var3;

   * Construct the object from its constituent parts, once only
public ImmutableBean(int var1, String var2, String var3) {
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;

   * A copy constructor
public ImmutableBean(ImmutableBean bean) {
this.var1 = bean.var1;
this.var2 = bean.var2;
this.var3 = bean.var3;

public int getVar1() {
return var1;

public String getVar2() {
return var2;

public String getVar3() {
return var3;

No comments: