Q2. How to create a singleton class in multi threaded environment ?
Question
Q2. How to create a singleton class in multi threaded environment ?
Solution
Creating a singleton class in a multi-threaded environment can be a bit tricky because you need to make sure that only one instance of the class is created even if multiple threads are trying to create an instance at the same time. Here is a step-by-step guide on how to do it in Java:
- Declare the constructor of the class as private. This will prevent other classes from instantiating this class.
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
}
- Create a static method that returns the instance of the class. This method needs to be synchronized to prevent multiple threads from creating an instance of the class at the same time.
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- The
getInstance()method checks if an instance of the class is already created. If not, it creates one. This is the key part of the singleton pattern.
This is a simple way to create a thread-safe singleton class in Java. However, synchronization is expensive in terms of performance. If performance is a concern, you might want to use the "double-checked locking" idiom, which reduces the use of synchronization.
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
In this version, the getInstance() method is not synchronized, but the part that creates the instance is. This reduces the need for synchronization and improves performance.
Similar Questions
How does the Singleton pattern ensure that a class has only one instance?*1 pointBy providing a global variable that holds the instance.B and CBy using a static method to handle instance creation.By making the class constructor private.
public class Singleton<T> { public static T getInstance() { if (instance == null) instance = new Singleton<T>(); return instance; } private static T instance = null;}
One of the following is not a method used to create a thread.*1 pointExtending a Thread classImplementing a Runnable interfaceExtending a MultiThread class
Is it possible to create a clone of a singleton object?a.Yesb.No
What is the purpose of the Lock class in the threading module?To stop a threadTo pause a threadTo ensure that only one thread accesses a resource at a timeTo create a new thread
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.