Java Program to Demonstrate the Non-Lazy Initialization Thread-Safe
Last Updated :
26 Jul, 2021
Java is one of the most popular Object-Oriented programming languages offered by Oracle which has a wide range of applications in website and application development explored by developers. Java along with some well-known and robust frameworks like Spring, Spring-Boot, etc. makes developer’s life easy while developing/coding Software. Java offers 2 ways of Object Instantiation (Object Instance Creation) are namely Eager and Lazy. This Article focus on Non-Lazy Instantiation (which means Eager Instantiation).
Threads in Java are small individual coding units that can execute separately (in parallel fashion on multiple cores of CPU) to enhance processing speed etc. So Thread-Safe in java means no matter how much ever threads are created and executed simultaneously the output or business logic of the program execution stays as expected or desired. For a simple example like a Singleton (Only 1 instance should be present during the execution of code and new/different instances of this class are allowed to be instantiated except the creation of the first one) class in java
Thus, this article tries to throw light on non-Lazy-Instantiation in the Thread-Safe environment and helps explain it with a practical illustration of the car-maker (manufacturer) case study example.
Implementation:
The following would be the approach to demonstrate to explain non-Lazy-Instantiation of Object by taking a CarMaker.java (Script below) as an example.
- We have a Car java class (which acts as a Singleton Class), so only one object must be created and supplied across the entire flow of the program.
- We have a CarMaker class (Runner class which has the main() method in it), which tries to take base Car instance and performs operations like design, paint, and enhance with it (in our exact case these are simple print statements with appropriate messages)
- We are having separate Threads being created for all the operations mentioned above to demonstrate a Thread-Safe behavior (in our case this means no matter even if simultaneous threads reach getCarIntance() method, only one instance will be circulating around the program)
- The order of thread execution may change, but the outcome of having single object creation (will be visible with same object ID printed on the terminal) using non-Lazy Instance creation will be satisfied here.
Example
Java
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
class Car {
private static final Car car = new Car();
private Car()
{
System.out.println( "New Car is Created" );
}
static Car getCarInstance()
{
return car;
}
}
class CarMaker {
public static void main(String args[])
{
Thread designCar = new Thread( new Runnable() {
public void run()
{
Car car = Car.getCarInstance();
System.out.println(
"Designing Car with id : " + car);
}
});
Thread paintCar = new Thread( new Runnable() {
public void run()
{
Car car = Car.getCarInstance();
System.out.println( "Painting Car with id : "
+ car);
}
});
Thread enhanceCar = new Thread( new Runnable() {
public void run()
{
Car car = Car.getCarInstance();
System.out.println( "Enhancing Car with id : "
+ car);
}
});
designCar.start();
paintCar.start();
enhanceCar.start();
}
}
|
Output:

Here we have compiled the program twice wherein the second time we have forcefully created the second ‘Car’ class object. Note that we can not create a second instance of the ‘Car’ class as the constructor for the second time is not visible. It will throw an error as depicted below in the pictorial hard-coded output in the underlined section which is thrown on the terminal as we compiled and run again by creating another object.
Output explanation:
Here in order to explain the non-Lazy Instantiation of Java class objects we take a simple case study of having a Car Marker who manufactures cars. It takes the base ‘Car’ vehicle and performs operations like Painting a Car, Designing a Car, and Enhancing the Car. To keep processing as simple as we can, we are having simple print statements in each operation along with the display of Car Object Id to make sure they are working on the same car.
As we can see in the output the order of execution for operations (Threads in this case) might differ, but the Car Object Id remains the same through the execution of the program to illustrate each operation (paint, design and enhance) is performed on the same car. As explained in the code comment “final” keyword at the singleton (Car) instance creation makes it thread-safe for execution, and thus we get the desired result of having the same Car Object throughout.
Conclusion: Do refer in order to figure out how “final” make the code thread-safe without having synchronization. Thus, the above article explains non-Lazy Instantiation (Eager Instantiation) of Java classes (Singleton classes) with the help of Car Maker case study example.
Similar Reads
Java Program to Demonstrate the Lazy Initialization Non-Thread-Safe
In recent years object-oriented programming has formed the pillars/bases of Website and Application (Software) Development. Java and Python are popular Object-Oriented programming languages out of which the former one is offered and maintained by Oracle, while the latter one is open-source. Java alo
8 min read
Java Program to Demonstrate the Lazy Initialization Thread-Safe
Java is a popular object-oriented programming language used by developers and coders for website/app development. The creation of a class object using a new keyword is referred to as object instantiation. Java by default allows users to define two ways of object instantiation which are Eager and Laz
7 min read
Java Program to Demonstrate the Nested Initialization For Singleton Class
A Singleton Class is capable of producing just a single instance. Every Singleton class has a getInstance method which returns its object. When the getInstance method is called for the first time, an object of the class is generated, stored, and then returned. On subsequent calls to getInstance, the
4 min read
Java Program to Demonstrate the Double-Check Locking For Singleton Class
One of the key challenges faced by junior developers is the way to keep Singleton class as Singleton i.e. the way to prevent multiple instances of Singleton class. Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application li
3 min read
Java Threading Programs - Basic to Advanced
Java threading is the concept of using multiple threads to execute different tasks in a Java program. A thread is a lightweight sub-process that runs within a process and shares the same memory space and resources. Threads can improve the performance and responsiveness of a program by allowing paral
3 min read
Java Program to Create a Thread
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. The slave thread is created as a result of the main thread. This is the
4 min read
How to make ArrayList Thread-Safe in Java?
In Java, Thread is the smallest unit of execution within the program. It represents an independent path of execution that can run concurrently with other threads. When dealing with multi-threaded applications, where multiple threads are accessing and modifying data concurrently, it's crucial to ensu
3 min read
How to Get the Id of a Current Running Thread in Java?
The getId() method of Thread class returns the identifier of the invoked thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused. Java allows c
4 min read
Java Multithreading - One Thread to Take Input, Another to Print on Console
Multithreading is a concept in which our program can do two or more tasks at the same time. Thread is the execution unit of any process. Every process has at least one thread which is called main thread. In this article, we will create a Java program that will do printing on the console until the us
4 min read
How to Use Locks in Multi-Threaded Java Program?
A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can ac
6 min read