Javatpoint Logo
Javatpoint Logo

Java Program to Demonstrate the Lazy Initialization Non-Thread-Safe

In 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-Safe

The 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:

  1. Define a Singleton class with a private static instance variable.
  2. Implement a private constructor for the Singleton class to prevent direct instantiation.
  3. The Singleton class should include a getInstance() method.
    • Verify whether the instance is null.
    • If the instance is null, create a new instance and assign it to the instance.
    • Return the instance.
  4. Implement a displayMessage() method in the Singleton class to print a message.
  5. Create a LazyInitialization class with the main() method.
  6. Inside the main() method:
    • Create three threads with t1, t2, and t3.
    • Each thread's run() method calls getInstance() and displayMessage() methods.
    • Start the execution of all three threads.
  7. End the program execution.

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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA