In Java, we can create a thread-safe Singleton pattern using an Enum
. Enum-based singletons are inherently thread-safe and provide a simple and concise way to implement singletons. Here’s an example:
public enum Singleton {
INSTANCE; // The single instance of the Singleton
// You can add instance methods and data members here
public void doSomething() {
// Implementation
}
}
In this example:
- We define an
enum
calledSingleton
, and we declare a single instance of theSingleton
enum calledINSTANCE
. - You can add instance methods and data members to the
Singleton
enum as needed.
Since enum instances are created only once by the JVM and are guaranteed to be thread-safe, you can use this approach to create a Singleton pattern without the need for explicit synchronization or double-checked locking.
You can access the Singleton instance using Singleton.INSTANCE
, and you can call its methods and access its data members as necessary.
Here’s how you would use it:
public class Main {
public static void main(String[] args) {
Singleton singleton = Singleton.INSTANCE;
singleton.doSomething();
}
}
This modern Java Singleton implementation is both concise and thread-safe, making it a recommended approach for Singleton design in Java.
Here is the Complete Program
public enum Singleton {
INSTANCE; // The single instance of the Singleton
// Data members and methods can be added here
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class SingletonDemo {
public static void main(String[] args) {
// Access the Singleton instance
Singleton singleton = Singleton.INSTANCE;
// Set a value
singleton.setValue(42);
// Access and print the value
System.out.println("Singleton value: " + singleton.getValue());
// Demonstrate that it's the same instance
Singleton anotherSingleton = Singleton.INSTANCE;
System.out.println("Are they the same instance? " + (singleton == anotherSingleton));
}
}
In this program:
- We define the
Singleton
enum with an instance calledINSTANCE
. You can add data members and methods to this enum as needed. - The
SingletonDemo
class demonstrates the usage of the Singleton. It accesses the Singleton instance, sets a value, retrieves the value, and demonstrates that it’s the same instance by comparing references.
When you run the SingletonDemo
class, you’ll see that it successfully maintains a single instance of the Singleton
and allows you to access its data members and methods.