LendKey

Friday, January 23, 2009

Thread-safe singlton instantiation

Very often that we need to get instance of a single which is initialized Lazily, meaning only when it is first be needed.

What we normally do is:



After reading a scary article about Java memory model, I realized this code does not always work in a multi-threaded environment:
http://www.ibm.com/developerworks/library/j-jtp03304/
and
http://www.ibm.com/developerworks/java/library/j-jtp02244.html
and
http://www.javaworld.com/jw-02-2001/jw-0209-double.html

The idea is complicated, but to describe it in a simple sentence, I would say:
Because modern compiler might reorder execution sequence of the commands, the code might fail under certain hardware/software environment.

So a safer solution is:


Because JVM guarantee initialization and execution order static inner classes, this solution is not only safe, but also faster than using volatile or synchronized keywords.

No comments: