In this video, explors how to use the Singleton pattern inside a multithreaded program. Learn how to avoid multiple Singletons inside a program running multiple threads.
- [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…when a method begins is a check to see…
Released
8/29/2018- What are creational design patterns?
- Avoid complex constructors
- Implementing the Builder pattern
- Multithreading with the Singleton pattern
- Using the Prototype pattern
- Implementing a simple Factory Method pattern
- Making code more flexible with the Abstract Factory pattern
Share this video
Embed this video
Video: Multithreading with the Singleton pattern