Singletons and Threads

If you want to lazy-initialize a singleton in a multithreaded environment, you have to take care to prevent multiple threads from initializing the singleton. In a multithreaded environment, a method is not guaranteed to run to completion before a method in another thread starts running. This opens the possibility, for example, that two threads will try to initialize a singleton at roughly the same time. Suppose that a method finds that a singleton is null. If another thread begins executing at that moment, it will also find that the singleton is null. Then both methods will proceed to initialize the singleton. To prevent this sort of contention, you need a locking ability to help coordinate methods running in different ...

Get Design Patterns Java™ Workbook 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.