Before I ask the question I like to provide the code for clarity. Below is my code for singleton class.
public class CoreData {
private boolean VarA;
private static CoreData instance = null;
protected CoreData() {
// Exists only to defeat instantiation.
}
public static CoreData getInstance() {
if(instance == null) {
instance = new CoreData();
}
return instance;
}
public boolean getVarA(){
return VarA;
}
public void setFirstTime(boolean B){
VarA = B;
}
}
Now I have few questions to ask
What will be difference if make the member variable VarA as static?
Can I initialize the member variable in the method getInstance()?
What is the best practice in initializing member variables in Singleton class?
What is the meaning of making this class as final?
What is the meaning of making the member variable final.
I am very new to java and OOPS. I am learning it now. I would be grateful if someone answer my queries to make my knowledge better.
Because you've only got one instance (or so you think - see below) making it static shouldn't make any difference.
Your code is not threadsafe! You could have two instances created. The reason is, after checking instance is null, another thread could also check and find it null - both threads would create instances and return them. One would "escape".
The traditional approach was "double checked locking", where the check is made inside a synchronized block, but as Bill Pugh pointed out in his famous article, that is a broken pattern. Java 1.5 introduced the volatile keyword to work around this problem, but it's still ugly code.
The modern best practice approach to lazy initialize the instance, is to use one of these patterns:
public class CoreData {
private static class InstanceHolder {
static CoreData INSTANCE = new CoreData();
}
public static CoreData getInstance() {
return InstanceHolder.INSTANCE;
}
}
or
public static enum CoreData {
INSTANCE;
// rest of class
}
Both are guaranteed by the language to create singletons, but the enum version is "iron-clad " - it is possible through a deserialization hack to affect the instance's state in the static holder class pattern. Apart from that slim vulnerability, both work. I prefer the first option in my code simply because it avoids class bloat.
What will be difference if make the member variable VarA as static?
It will be harder to make it non singleton later
Can I initialize the member variable in the method getInstance()?
Yeah. Why not. But actually constructors are done for this.
What is the best practice in initializing member variables in Singleton class?
By the best practice you should use some IoC and don't put any code about scope in your logic code.
What is the meaning of making this class as final?
You should use private constructor instead of protected one or make it final to prevent creating several instances by extending. Like new CoreData(){};
What is the meaning of making the member variable final?
I believe all variables should be final by default. Also it can help you with multi threading issues.
Related
This question already has answers here:
singleton public static final
(5 answers)
Closed 3 years ago.
For example:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor suppresses
// default public constructor
private Singleton() {};
public static Singleton getInstance() {
return INSTANCE;
}
}
Why can't I set the INSTANCE public, and access it by Singleton.INSTANCE? What will it cause?
You technically can and in this code, it will have no effect - it will behave the same.
The reasons we use getters in general are:
A good habit - people will be surprised to see you access a variable directly
Flexibility - if you have a hundred places around the code calling the getter, it's easy enough to change the method behavior (like returning new Singleton() every time instead of accessing the static variable). Not so easy if that hundred places access the variable directly.
Because its good practice to encapsulate your instance in order to avoid boiler plate code and in that case you need to use static block to initialize your object which is better if you initialize your object when needed (lazy load) may be benefit of your memory usage.
You could technically make Singleton.INSTANCE public because it is final. However, from the perspective of the user of your API, it is not obvious that Singleton.INSTANCE is final without looking at the contents of the Singleton class, and a user might be tempted to try to reassign Singleton.INSTANCE from a different class.
Making Singleton.INSTANCE only accessible through Singleton.getInstance() makes it obvious to everyone that it is not possible to reassign the variable.
I know this question is weird but just wondering: is there any way to create multiple instances of a Singleton class in Java?
My situation is like this:
I have an Singleton class and i need to have 2 objects/instances of that class. Is there any way to modify class to be able to create multiple instances?
My class:
public class SingletonClass {
private static SingletonClass sSoleInstance;
//private constructor.
private SingletonClass(){
//Prevent form the reflection api.
if (sSoleInstance != null){
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static SingletonClass getInstance(){
if (sSoleInstance == null){ //if there is no instance available... create new one
sSoleInstance = new SingletonClass();
}
return sSoleInstance;
}
}
One can use the enum pattern to create singletons; like
public enum Whatever {
INSTANCE;
}
Turning that into a Bi-Singleton goes like:
public enum Whatever {
INSTANCE, YETANOTHER
}
For the record: I just made up the word "bi-singleton"; simply as this makes close to 0 sense from a conceptual point of view. If you need more than one instance, it is not a singleton; period. So your question sounds more like an XY problem.
And just a note: consider using that enum solution; as it is thread safe by default; the code you are using is not. But before making changes, do a bit of research to understand the pros and cons of those approaches.
Absolutely valid question with a valid use case - in a nutshell you can have multiple instances of a class with a private constructor when employing static factory methods. You ensure that your class cannot be instantiated from the outside world by making the constructor private, but at the same the class in question can instantiate itself as many times as it pleases.
Check this article for details and code samples.
Hope that helps.
According to this post, the thread-safe singleton class should look as below. But I'm wondering whether there's a need to add volatile keyword to static CrunchifySingleton instance variable. Since if the instance is created and stored in CPU cache, at which time it is not written back to main memory, meanwhile, another thread invoke on getInstance() method. Will it incur an inconsistency problem?
public class CrunchifySingleton {
private static CrunchifySingleton instance = null;
protected CrunchifySingleton() {
}
// Lazy Initialization
public static CrunchifySingleton getInstance() {
if (instance == null) {
synchronized (CrunchifySingleton.class) {
if (instance == null) {
instance = new CrunchifySingleton();
}
}
}
return instance;
}
}
I echo #duffymo's comment above: lazy singletons are nowhere near as useful as they initially appear.
However, if you absolutely must use a lazily-instantiated singleton, the lazy holder idiom is much a easier way to achieve thread safety:
public final class CrunchifySingleton {
private static class Holder {
private static final CrunchifySingleton INSTANCE = new CrunchifySingleton();
}
private CrunchifySingleton() {}
static CrunchifySingleton getInstance() { return Holder.INSTANCE; }
}
Also, note that to be truly singleton, the class needs to prohibit both instantiation and subclassing - the constructor needs to be private, and the class needs to be final, respectively.
Yep, if your Singleton instance is not volatile or even if it is volatile but you are using sufficiently old JVM, there's no ordering guarantees for the operations in which the line
instance = new CrunchifySingleton();
decomposes with regard to the volatile store.
The compiler can then reorder these operations so that your instance is not null (because memory has been allocated), but is still uninitialized (because its constructor still hasn't been executed).
If you want to read more about the hidden problems around Double-Checked Locking, specifically in Java, see The "Double-Checked Locking is Broken" Declaration.
The lazy holder idiom is a nice pattern that generalizes well for general static field lazy loading, but if you need a safe and simple Singleton pattern, I'd recommend what Josh Bloch (from Effective Java fame) recommends - the Java Enum Singleton:
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
The code how you quoted it is broken in Java. Yes, you need volatile and at least Java 5 to make the double-checked idiom thread safe. And you should also add a local variable in your lazy initialization to improve performance. Read more about it here: https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
Yes, making volatile will gaurantee that every time any thread is trying to access your critical section of code, the thread reads the data from memory itself and not from hread cache.
You need volatile in this case but a better option is to use either an enum if it is stateless
enum Singleton {
INSTANCE;
}
however stateful singletons should be avoid every possible. I suggest you try creating an instance which you pass via dependency injection.
Could the uniqueeInstance have one and only one instance?
public class A {
private static A uniqueInstance = new A();
private A() {}
public static A getInstance() {
return uniqueInstance;
}
}
This is a Singleton pattern, it's purpose is to have only one possible instance for a class.
This is why you have a private constructor , so that no other class can attempt to instantiate it directly.
Here are more elaborate thoughts for possible uses of a Singleton :
When to use the Singleton
It is not guaranteed.
By reflection you are easy to get more instances.
The only way to guarantee that you have exactly one instance is to use an enum:
enum Holder {
INSTANCE;
//Keep in Mind of A you may still have more instances. if you want to have the
//guarantee to have only one instance you may need merge the whole class
//into an enum (which may not be possible)
public A uniqueInstance = new A();
}
Other ways like throwing an exception in the constructor are generally also possible. But not completely secure since there are ways to create an Object without calling any constructor.
public enum YourSingleton {
INSTANCE;
public void doStuff(String stuff) {
System.out.println("Doing " + stuff);
}
}
YourSingleton.INSTANCE.doStuff("some stuff");
Here is the original link,
http://electrotek.wordpress.com/2008/08/06/singleton-in-java-the-proper-way/
I am asking why we can call the function doStuff this way in Java.
In Java, enum can do everything that class can [1]. YourSingleton.INSTANCE creates an instance of YourSingleton, so you can then invoke methods as if it were a regular class instance, which it basically is.
See the official Java docs for a more in-depth discussion on Enum Types: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
[1] enum does not have a practical implementation of inheritance. Since all enum types implicity inherit java.lang.Enum and Java does not support multiple inheritance, you cannot extend anything else.
The Traditional way to implementing singleton is fine, but to maintain its Status as true singleton, it needs to protect itself from sophisticated Serialization and Reflection Attacks. The general way of doing this, is by making the class Implement Serializable, make all instance fields Transient and also implement a readResolve method. (that return the same singleton instance).
The Enum Singleton pattern provides all these features out of the box. But the main reason, I like the Enum variant is its readability. According to me, it conveys what it does, in a much more concise fashion, than a traditional singleton.( You do not have to explain to a new developer, all the vagaries involved in serialization and how serialization might break the singleton guarantee and why you need readResolve method etc etc..)
I know this is not really what you asked for but this is what I do when I need a class to be a singleton, which may help. I create one static getInstance method that either creates and returns a new instance of the class if none exist or I return the existing reference of itself, and I make the constructor for this class private.
For example:
public class NameOfClass{
private static NameOfClass variableReferencingThisClass=new NameOfThisClass();
private NameOfClass(){}
public static NameOfClass getInstance(){
return variableReferencingThisClass;
}
}
You can also use the double-lock singleton creation. Assuming the class is MyObject, has a private constructor, and has a declared a static field instance as null. However, this is not a guarantee that 2 singletons will not end up getting created, but is a much closer attempt to thread safety than a single check.
public static MyObject getInstance()
{
if (instance == null)
{
synchronized(MyObject.class) {
if (instance == null)
instance = new MyObject();
}
}
return instance;
}