Java singleton example

Brad 146 Published: 09/24/2024

Java singleton example

Here is a basic example of how you could implement a Singleton class in Java:

public class Singleton {

// Private constructor to prevent instantiation from outside the class

private Singleton() {}

// Static instance variable for holding the single instance

private static Singleton uniqueInstance;

// Static method for getting the single instance

public static Singleton getInstance() {

if (uniqueInstance == null) {

synchronized (Singleton.class) { // Synchronizing access to the instance

if (uniqueInstance == null) {

uniqueInstance = new Singleton(); // Creating a new instance if none exists

}

}

}

return uniqueInstance;

}

public void doSomething() {

System.out.println("I am doing something");

}

public static void main(String[] args) {

Singleton singleton1 = Singleton.getInstance();

Singleton singleton2 = Singleton.getInstance();

// Both instances should be the same

if (singleton1 == singleton2) {

System.out.println("Both are the same instance");

} else {

System.out.println("They are different instances");

}

singleton1.doSomething();

}

}

In this example, we create a Singleton class that has a private constructor to prevent instantiation from outside the class. It also has a static instance variable uniqueInstance for holding the single instance of the Singleton.

The getInstance() method is used to get the single instance. If no instance exists (i.e., uniqueInstance == null), it creates a new one and assigns it to uniqueInstance. This ensures that only one instance is created, regardless of how many times you call getInstance().

In the main() method, we test if two calls to getInstance() return the same instance. Since they are singletons, they should be the same instance.

This example does not use lazy initialization (i.e., creating the instance only when it is first needed). This can be useful for large or complex instances that take a long time to create. To implement lazy initialization in this Singleton class, you would add a check in getInstance() for whether an instance already exists before creating a new one:

public static Singleton getInstance() {

if (uniqueInstance == null) {

synchronized (Singleton.class) { // Synchronizing access to the instance

if (uniqueInstance == null) {

uniqueInstance = new Singleton(); // Creating a new instance if none exists

}

}

}

return uniqueInstance;

}

However, using lazy initialization with synchronization can be problematic because it may cause performance issues. A better approach might be to use double-checked locking:

public static Singleton getInstance() {

if (uniqueInstance == null) {

synchronized (Singleton.class) { // Synchronizing access to the instance

if (uniqueInstance == null) {

uniqueInstance = new Singleton(); // Creating a new instance if none exists

}

}

}

return uniqueInstance;

}

However, this approach is not thread-safe in all Java environments. Therefore, it's generally best to use lazy initialization without synchronization:

private static class SingletonHelper {

public static Singleton getInstance() {

if (uniqueInstance == null) {

uniqueInstance = new Singleton(); // Creating a new instance if none exists

}

return uniqueInstance;

}

private SingletonHelper() {}

}

public static Singleton getInstance() {

return SingletonHelper.getInstance();

}

In this approach, uniqueInstance is only initialized when it's first needed.

Java singleton with parameters

A Java singleton with parameters!

In Java, a singleton is a design pattern that restricts the instantiation of a class to a single instance. This is achieved by making sure that the constructor is private and providing a public static method called getInstance() that returns an instance of the class.

Now, let's talk about creating a Java singleton with parameters!

When we need to create a singleton with parameters, it becomes more complex as we need to ensure that the same set of parameters are used throughout the application. We can achieve this by passing parameters to the constructor and then storing them in instance variables.

Here is an example:

public class SingletonWithParams {

private static class LazyHolder {

private static final SingletonWithParams INSTANCE = new SingletonWithParams("param1", "param2");

}

public static SingletonWithParams getInstance() {

return LazyHolder.INSTANCE;

}

private String param1;

private String param2;

private SingletonWithParams(String param1, String param2) {

this.param1 = param1;

this.param2 = param2;

}

}

In the above example, we are passing two parameters param1 and param2 to the constructor. The instance of this class is stored in a private static variable called INSTANCE.

Now, when you want to access the singleton with parameters, you can use the getInstance() method:

SingletonWithParams singleton = SingletonWithParams.getInstance();

This way, you are sure that all instances of the singleton will have the same set of parameters.

Benefits:

Single instance: The singleton ensures that there is only one instance of your class. Parameterized instance: By passing parameters to the constructor and storing them in instance variables, you can ensure that each instance has the same set of parameters. Lazy loading: The LazyHolder class ensures that the instance is not created until it is first requested.

However, be aware of the following:

Drawbacks:

Global state: Singletons maintain global state, which can make your program harder to understand and test. Immutability: Since singletons are created only once, they cannot change their internal state or behave differently in different parts of your program.

In conclusion, creating a Java singleton with parameters is possible but requires careful consideration of the trade-offs involved. It's essential to weigh the benefits against the drawbacks and choose the right approach for your specific use case.

Would you like me to elaborate on any part?