Java: Double-checked locking

Published: Monday, 28 August 2006

Double checked locking anti-pattern

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
    1. memory allocated but object not ready, not null.
    1. 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