Skip to content

Java: Double-checked locking

Double checked locking does not work because a line such:

Resource r = new Resource();

does not happen atomically.

Instead variable r changes state from

  1. null
  2. memory allocated but object not ready, not null.
  3. then properly initialised.

If another thread has a reference to 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