Providing a unique object instance with a double-checked locking pattern
The double-checked locking pattern solves the problem of an application requiring only one instance of a particular class at runtime.
Motivation
The Java platform is multi-threaded by default, as we learned in Chapter 2, Discovering the Java Platform for Design Patterns. It’s not just the garbage collection threads that take care of the main program lifecycle. Different frameworks introduce additional tread models, which may have an unintended impact on a class institution’s process. A double-checked locking pattern ensures that only one instance of a class is present at runtime. This state can become challenging in a multi-threaded environment, as it may depend on its implementation.
Sample code
Let’s use a simple Vehicle
instance to demonstrate the importance of a double-checked locking pattern in a multithreading environment. The example presents two different implementations...