Wednesday, November 26, 2008

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() {

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.

No comments:

Post a Comment