Java: Double-checked locking

Double checked locking anti-pattern

Apparently double checked locking does not work because a line such as r = new Resource();

      Resource r = new Resource();

does not happen atomically. Instead variable r changes state from 1) null, 2) memory allocated but object not ready, 3) then properly initialised.

If another thread has a hold of r, then it may try to use it when r is in the state "memory allocated but object not ready", which can lead to bugs

Published: Monday, 28 August 2006