Wednesday, November 26, 2008

Java : final modifier and Java memory model : Answered

In my last post I had asked a question about the visibility guarantee of the final modifier in java. Well, my colleague Alex Miller simultaneously blogged about it and beat me by answering it too.

Anyways, the answer to the question lies in the guarantee that the JMM gives for final variables. Basically it gives the guarantee that the state of the final variable (in this case the map) at the time the construction is complete is published to all threads without the need of any extra memory barrier.

More proofs and discussions can be found at Alex's blog.

Java : final modifier and Java memory model

Today while I was browsing some code, I came across something like this.

public SomeClass {

private final LinkedHashMap map = new LinkedHashMap();

SomeClass() {
init();
}

private void init() {
for (int i = 1; i < length ++i) {
// do some initialization here ;
map.put(key, value);
}
}

// Some read method : Is this thread safe ?
public Object get(Object key) {
return map.get(key);
}

}


The map is declared as final. Notice that the map is never mutated outside the constructor but is mutated in the constructor *after* the assignment in the init() method.


Now assuming that the object is properly constructed, i.e. the reference is not leaked until construction is complete and without making any assumption about how the reference is leaked to other threads after construction, can you tell if the get() method in the class is thread safe ? If not,why ?

I asked this question to my colleagues and I got some very interesting answers. I will post the answer and the explanation in another entry.