Code Curve

Code Curve

Share

I specialize in Spring Boot, Spring Security, AWS, React JS, and Core Java development.

✅ Code Curve | Tech Education
🚀 Java Full-Stack Development
💡 System Design & Microservices
☁️ AWS, Cloud & DevOps Concepts
🤖 AI & GenAI for Developers
🎯 Interviews • Projects • Career Growth I’m Mohd Fakhre Alam, a passionate Java Full-Stack Developer and professional trainer helping students, developers, and working professionals upgrade their skills in modern industry-level technologies. With h

01/06/2026

Yesterday I posted below Question :

String s1="code";
String s2="code";

System.out.println(s1==s2); //true
System.out.println(s1.equals(s2));//true

please Find Explaination in given post

31/05/2026

Hey Everyone Lets find out the output,
This Question has been asked in IRIS Software

22/05/2026

Let's learn

25/03/2026

Follow for Java interview Question .
You will get everyday Java interview Question

Call now to connect with business.

25/03/2026

Interview_Question_1: Complete Detail with coding Example
Q) How to make singleton class in Java.

⭐ A Singleton is a design pattern that ensures:
Only one object of a class is created.
It provides a global access point to that object.

Useful when:

You want a single configuration manager
Database connection pool
Logger
Caches
Thread pools

⭐ Why Singleton Is Not easy in Java
Creating “only one object” sounds simple, but Java class creation is affected by:

Multi-threading
Reflection
Serialization
Class loaders

⭐ A proper Singleton handles all of these issues.

A singleton class must have:

Requirement Meaning
private constructor Prevents direct creation using new
static instance Holds the single shared object
public static getInstance() Returns the single object

EAGER INITIALIZATION (Simplest & Thread‑Safe):
package com.codecurve.singletonclassdemo;

public class DataBaseConnectionSingletonEagerLoading {

/*
1. EAGER INITIALIZATION (Simplest & Thread‑Safe)
🔍 When to use?

When object is lightweight
When you always need the instance

✔️ Pros

Simple
Thread-safe (class loading is thread-safe)

❌ Cons

Instance is created even if unused

*/

//instance will create at the time of class loading only once
private static final DataBaseConnectionSingletonEagerLoading instance =
new DataBaseConnectionSingletonEagerLoading();

//make constructor private will prevent object creation from outside the class
private DataBaseConnectionSingletonEagerLoading(){

}

//will get object by calling getInstance method
public static DataBaseConnectionSingletonEagerLoading getInstance() {
return instance;
}

}

2. LAZY INITIALIZATION
package com.codecurve.singletonclassdemo;

public class DataBaseConnectionSingletonLazyLoading {

//make constructor private will prevent object creation from outside the class
private DataBaseConnectionSingletonLazyLoading() {
}

/*
LAZY INITIALIZATION (Non-Thread‑Safe)
When to use?

When instance creation is expensive
BUT NOT for multithreaded apps

In Multithreaded environment class will not work as singleton

private static DataBaseConnectionSingletonLazyLoading instance;

public static DataBaseConnectionSingletonLazyLoading getInstance() {
if (instance == null) {
instance = new DataBaseConnectionSingletonLazyLoading(); // ❌ Not thread-safe
}
return instance;
}
*/

/*
To make THREAD‑SAFE LAZY INITIALIZATION using synchronized, it will work in multithreaded environment

✔️ Pros
Thread-safe

❌ Cons
Slow due to synchronized on every call

❗ Problem With This Approach
After the instance is created, the synchronized still locks the entire method for every call.
Result:
Slow performance under heavy load
Many threads waiting even though they don’t need to

private static DataBaseConnectionSingletonLazyLoading instance;
public static synchronized DataBaseConnectionSingletonLazyLoading getInstance() {
if (instance == null) {
instance = new DataBaseConnectionSingletonLazyLoading();
}
return instance;
}
*/

/*
DOUBLE-CHECK LOCKING (Best lazy until Java 5)
Most popular thread-safe lazy singleton
Its recommended approach

✔️ Pros
High performance
Thread-safe
Lazy loading

🧠 Step 1: First if (instance == null) — Quick Check
This check happens without locking.
➡ ️ Most of the time, the instance is already created, so threads skip everything and return it immediately.

Step 2: synchronized block — Lock only when needed
Only when the instance is missing do threads enter the synchronized block.
➡️ Fewer threads wait.
➡️ Locking happens only during first‑time creation.

🔍 Step 3: Second if (instance == null) — Double Check
Once inside the synchronized block, we check again.
Why check twice?
Because multiple threads may reach the first if simultaneously.
Without the second check, they could create multiple objects.

⭐ Why volatile is required?
In multi‑threading, instruction reordering can cause threads to see half‑constructed objects.

Example of danger:
Thread A starts creating object
→ Memory is allocated
→ Reference is assigned to instance
→ But constructor is not fully finished

Thread B sees a non-null instance
→ Tries to use it
→ Crash / weird behavior
volatile prevents this.

*/

private static volatile DataBaseConnectionSingletonLazyLoading instance;
public static DataBaseConnectionSingletonLazyLoading getInstance() {
if (instance == null) { // 1st check
synchronized (DataBaseConnectionSingletonLazyLoading.class) {
if (instance == null) { // 2nd check
instance = new DataBaseConnectionSingletonLazyLoading();
}
}
}
return instance;
}

}

3. Best Singleton Example (Bill Pugh Singleton)
package com.codecurve.singletonclassdemo;

public class DataBaseConnectionSingletonBestPractice {

/*
Best Singleton Example (Bill Pugh Singleton)
Bill Pugh (full name: William Worthington “Bill” Pugh Jr.)
is a well‑known American computer scientist

The Bill Pugh Singleton approach is fully applicable after Java 5,
and in fact it became even more reliable because of the revised Java Memory Model introduced in Java 5.

✅ Why It Works After Java 5
The Bill Pugh approach relies on Java’s class-loading mechanism, not on volatile or synchronization.
Java class loading guarantees:

A class is loaded and initialized only once by one thread.
The static inner class is initialized lazily—only when accessed.
Initialization of static fields is thread-safe by definition.

These guarantees became formally specified and strengthened in the new Java Memory Model introduced in Java 5,
Making the pattern completely safe and widely recommended.

✅ Why It’s Preferred Over Double‑Checked Locking Post‑Java 5
Although double‑checked locking (with volatile) became safe after Java 5, the Bill Pugh approach is:

Simpler (no volatile, no double checks)
Faster (no runtime locking at all)
Cleaner (no complex concurrency code)
100% guaranteed by JVM class initialization rules

Most Java experts recommend Bill Pugh’s pattern unless you need Enum Singleton.

🔥 Bill Pugh Singleton vs Double‑Checked Locking (DCL)
Since the user only asked for a comparison, this answer is concise, clear, and to the point.

✅ 1. Conceptual Explanation
🔹 Bill Pugh Singleton
Uses a static inner helper class.
The Singleton instance is created only when the inner class is loaded.
Key idea:
JVM guarantees that class loading is thread‑safe, so no need for synchronized or volatile.

🔹 Double‑Checked Locking (DCL)
Uses lazy initialization + synchronization, but only when creating the instance.
Key idea:
Check null → lock → check again → create instance.
Requires volatile to avoid instruction reordering.

*/

// 1. Private constructor — prevents creating objects from outside
private DataBaseConnectionSingletonBestPractice() {
System.out.println("Singleton Object Created");
}

// 2. Static inner class — holds the Singleton instance
private static class Holder {
private static final DataBaseConnectionSingletonBestPractice INSTANCE = new DataBaseConnectionSingletonBestPractice();
}

// 3. Global access method — returns the same instance every time
public static DataBaseConnectionSingletonBestPractice getInstance() {
return Holder.INSTANCE;
}

// Example method
public void connect() {
System.out.println("Connected to database!");
}
}

4. Main Class to Test above code
package com.codecurve.singletonclassdemo;

public class MainSingleton {

public static void main(String[] args) {

DataBaseConnectionSingletonBestPractice db1 = DataBaseConnectionSingletonBestPractice.getInstance();
DataBaseConnectionSingletonBestPractice db2 = DataBaseConnectionSingletonBestPractice.getInstance();

db1.connect();

System.out.println(db1 == db2); // true → both are same object

}
}

Call now to connect with business.

27/11/2025

🚀 Welcome to Code Curve – Where Developers Take Shape

Hello everyone!
I’m excited to finally share my journey and open this new chapter called Code Curve.

From today, Code Curve is not just a page—it’s a community for developers, learners, and dreamers who want to grow in the world of Java & Full-Stack development.

What you can expect here:

✅ Spring Boot Interview Questions (Real Industry Level)
✅ Core Java Concepts the way companies expect
✅ Daily learning notes, challenges & exercises
✅ Guidance for beginners → professionals
✅ Career-focused | Practical | Project-oriented content

Because learning is not just about reading documentation…
It’s about mastering the skill that shapes your future.

Call now to connect with business.

Want your school to be the top-listed School/college in Delhi?
Click here to claim your Sponsored Listing.

Category

Telephone

Website

Address

Inder Enclave Phase 2 Kirari Suleman Nagar Delhi Near Bilal Masjid
Delhi
110086