Java Program to Demonstrate the Lazy Initialization Non-Thread-SafeIn Java, lazy initialization is a technique where an object is only created once it is first needed. Utilizing such a method can be beneficial for objects that are expensive to create or may not be needed at all. However, lazy initialization might cause issues in multithreaded applications. It is because multiple threads may try to access the object simultaneously, and if the object is not thread-safe, this can lead to data corruption. Approach: Lazy Initialization with Non-Thread-SafeThe code uses the volatile keyword to make the instance variable thread-safe. The volatile keyword makes sure that every thread sees the instance variable's most recent value. The synchronized keyword is used to lock the Singleton.class object when the getInstance() method is called. It makes sure that only one thread at once may use the getInstance() method. Algorithm:
Note: The code demonstrates the lazy initialization non-thread-safe approach, where multiple threads can potentially create multiple instances of the singleton class.Implementation:Filename: LazyInitialization.java Output: Singleton object created Lazy Initialized Singleton Singleton object created Lazy Initialized Singleton Singleton object created Lazy Initialized Singleton Explanation: The getInstance() method could be more efficient using the double-checked locking pattern. The pattern avoids the overhead of locking the getInstance() method every time it is called. The Singleton class could be made more reusable by making it abstract. It would allow other classes to extend the Singleton class and inherit its lazy initialization behavior. The Singleton class could be made more extensible by providing a way for subclasses to customize the getInstance() method. It would allow subclasses to control how the Singleton object is created. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India