From the course: Java Design Patterns: Creational

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Multithreading with the Singleton pattern

Multithreading with the Singleton pattern - Java Tutorial

From the course: Java Design Patterns: Creational

Start my 1-month free trial

Multithreading with the Singleton pattern

- [Instructor] Problems can occur when using the singleton pattern in a multi-threaded program. Java supports concurrency which means multiple units of execution can run at the same time. If a program has multiple threads that are using the PrintSpooler class it is possible for two different objects to be created. In this example, the ResourceManager class has two threads running at the same time. Thread one is started and right after thread two is also started. Both threads call a getInstance method of the PrintSpooler class. Thread one calls the method first. The first line of the getInstance method checks if the initialized flag is set to true or false. As this is the first time the PrintSpooler class has been used in the program this is set to false. So the thread carries onto the second line when it creates a new principle object. It then enters the code to initialize the object. At this time the second thread might call a getInstance method. Again, the first thing that happens…

Contents