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.
Related
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.
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.
it might be stupid question, but I dont know the answer to it and I dont know where to search the answer, so it would be nice if someone could help me.
I've a class (lets name it A) with different members and methods. I use the methods of this class in another class (lets name it B).
For every B-Object created I want to use the SAME instance of A. Is that possible?
Actually I have a constructor in B where I call A a = new A(); Of course I always get different instances of this class.
How can I now change this? I know it could be possible to solve it with spring framework (inject always the same object into the instances of B), but I cant use it. How else could this problem be solved?
Thank you very much for your help! :-)
Yes its possible. You need to define a singleton instance of classA that is static, and use it wherever you want.
So there are multiple ways of doing this:
public class ClassA {
public static ClassA classAInstance = new ClassA();
}
then anywhere you can do
ClassA.classAInstance.whatever();
This is simple, but it might be enough for you.
If you really want to use the singleton pattern, look here for a Java example. The advantage of this approach is that it makes sure that you only have 1 classA instance.
To elaborate on other answers:
public class A
{
private static A instance;
private A()
{
...
}
public static A getInstance()
{
if (instance == null)
instance = new A();
return instance;
}
...
public void doSomething()
{
...
}
}
And then call in B like this:
A.getInstance().doSomething();
It sounds like you may want A to be a Singleton.
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object.
This means your existing code will have to modified to use some kind of getInstance() method, but once that change has been made all instances of class B will use a single instance of class A.
Here is a direct link to the: simplest example from the above site.
Just use a static class and make sure it's public.
Though you can use singleton design pattern to share the same instance every-time but if you want to use a same instance with parameters(overloaded constructor)..you cannot use SINGLETON
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;
}
This question, like my previous question, references Effective Java. This time I have quite a few sub-questions.
A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible() method. If you need to defend against this, modify the constructor.
How, exactly, can a private constructor be invoked? And what is AccessibleObject.setAccessible()?
What approach do you experts follow with singletons?
// Approach A
public class Test{
public static final Test TestInstance = new Test();
private Test(){ ... }
.
.
.
}
// Approach B
public class Test{
private static final Test TestInstance = new Test();
private Test(){ ... }
public static Test getInstance() { return TestInstance; }
.
.
.
}
Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?
What if I try to clone the class/object?
a single-element enum type is the best way to implement a singleton.
Why? How?
A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
Obviously a private constructor can be invoked by the class itself (e.g. from a static factory method). Reflectively, what Bloch is talking about is this:
import java.lang.reflect.Constructor;
public class PrivateInvoker {
public static void main(String[] args) throws Exception{
//compile error
// Private p = new Private();
//works fine
Constructor<?> con = Private.class.getDeclaredConstructors()[0];
con.setAccessible(true);
Private p = (Private) con.newInstance();
}
}
class Private {
private Private() {
System.out.println("Hello!");
}
}
2.What approach do you experts follow with singletons:
...
Typically, the first is favoured. The second (assuming you were to test if TestInstance is null before returning a new instance) gains lazy-loading at the cost of needing to be synchronized or being thread-unsafe.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, the above consideration is irrelevant.
Isn't the second approach more flexible in case we have to make a check for new instance every time or same instance every time?
It's not about flexibility, it's about when the cost of creating the one (and only) instance is incurred. If you do option a) it's incurred at class loading time. That's typically fine since the class is only loaded once it's needed anyway.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, in both cases the Singleton will be created at class load.
What if I try to clone the class/object?
A singleton should not allow cloning for obvious reasons. A CloneNotSupportedException should be thrown, and will be automatically unless you for some reason implement Cloneable.
a single-element enum type is the best way to implement a singleton. Why? and How?
Examples for this are in the book, as are justifications. What part didn't you understand?
Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most over-used patterns. It's gotten to the point that some consider them an "anti-pattern". The best advice is to "use them wisely."
For a great introduction to this, and many other useful patterns (personally, I find Strategy, Observer, and Command to be far more useful than Singleton), check out Head First Design Patterns.
A priviledged cleint can invoke the private constructor reflectively with
the aid of the
AccessibleObject.setAccessible method,
If you need to defend this, modify the
constructor. My question is: How
exactly can a private constructor is
invoked? and what is
AccessibleObject.setAccessible??
You can use java reflection to call private constructors.
What approach do you experts follow with singletons:
I am a fan of using enum to actually do this. This is in the book also. If that's not an option, it is much simpler to do option a because you don't have to check or worry about instance being already created.
What if I try to clone the
class/object?
Not sure what you mean? do you mean clone() or something else that I don't know of?
a single-element enum type is the best way to implement a singleton.
Why? and How?
Ahh my own answer. haha. This is the best way because in this case, the java programming language guarantees a singleton instead of the developer having to check for a singleton. It's almost as if the singleton was part of the framework/language.
Edit:
I didn't see that it was a getter before. Updating my answer to this - it's better to use a function such getInstance because you can control what happens through a getter but you can't do the same if everybody is using a reference directly instead. Think of the future. If you ended up doing SomeClass.INTANCE and then later you wanted to make it lazy so it doesn't load right away then you would need change this everywhere that its being used.
The first rule of the Singleton (Anti-) Pattern is don't use it. The second rule is don't use it for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, especially if it is a dependency of those classes. Use dependency injection instead. There are valid uses for Singletons, but people have a tendenecy to badly misuse them because they're so "easy" to use. They make it very difficult to test classes that depend on them and make systems inflexible.
As far as your questions, I think 1, 2 and 3 can all be answered by saying "use an enum-singleton". Then you don't need to worry about constructor accessiblity issues, clone()ing, etc. As far as 4, the above is a good argument for them. I also have to ask, did you read the section in Effective Java that explicitly answers your question?
Example singleton lazy init:
Class main:
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
Class singleton:
public class Singleton {
private static Singleton instance;
public String value;
private Singleton (String s){
this.value =s;
}
public static Singleton getInstance(String param) {
if (instance == null)
instance = new Singleton(param);
return instance;
}
}
When start application, console will contains next strings:
first
first
first
\|/ 73