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