Java Program to Demonstrate the Non-Lazy Initialization Thread-SafeIn Java, threads are independent units of execution that can run concurrently, allowing for improved processing speed by utilizing multiple CPU cores. Thread safety in Java refers to the property of a program or code that can handle and execute correctly regardless of the number of threads created and executed simultaneously. When we say a program is thread-safe, it means that the program's output or behavior remains consistent and expected even when multiple threads are accessing and modifying shared resources concurrently. It is particularly important when multiple threads access and manipulate the same data or resources. The Singleton design pattern is A common example demonstrating the need for thread safety. In the Singleton pattern, we want to ensure that only one instance of a class is present throughout the program's execution. Any attempt to create new instances after the first one should return a reference to the existing instance. Making a Singleton class thread-safe ensures that even if multiple threads try to create instances concurrently, only one instance will be created. It prevents data inconsistencies, race conditions, and unexpected behavior that could occur if multiple instances of the Singleton class were allowed. Filename: CarManufacturing.java Output: Thread 1: Vehicle ID - Vehicle@7f5460e1 Thread 2: Vehicle ID - Vehicle@7f5460e1 Thread 3: Vehicle ID - Vehicle@7f5460e1 Explanation: Thread 1 creates a new instance of the Vehicle class. Thread 2 calls the getInstance() method and gets the same instance of the Vehicle class created by Thread 1. Thread 3 calls the getInstance() method and gets the same instance of the Vehicle class created by Thread 1. All three threads print the ID of the Vehicle class. The ID is 0 because all three threads get the same class instance. Next TopicJava Static Field Initialization |
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