A Variant: The Double-Checked Locking Pattern

This pattern only applies to multithreaded applications. If you are not involved with multithreaded applications you might want to skip this section. This section assumes that you have a basic understanding of multithreaded issues, including synchronization.

A problem with the Singleton pattern may arise in multithreaded applications.

Suppose two calls to getInstance() are made at exactly the same time. This can be very bad. Consider what can happen in this case:

  1. The first thread checks to see if the instance exists. It does not, so it goes into the part of the code that will create the first instance.

  2. However, before it has done that, suppose a second thread also looks to see if the instance member ...

Get Design Patterns Explained: A New Perspective on Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.