Java Singleton Pattern - java

Edit: Answered - error was method wasn't static
I'm used the Singleton Design Pattern
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
My question is how do I create an object of class Singleton in another class?
I've tried:
Singleton singleton = new Singleton();
// error - constructor is private
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context
What is the correct code?
Thanks,
Spencer

Singleton singleton = Singleton.getInstance();
is the correct way. Make sure your getInstance() method is indeed static.
Since your Singleton implementation is far from being safe - your object can be instantiated via reflection, you may want to create a singleton based on enum

Singleton singleton = Singleton.getInstance(); should work -- that error doesn't make sense, given your code; are you sure you're reporting it correctly? (It would make sense if you had forgotten to make the getInstance method static, which you've done in your code above.)
The code you've given us for the class is correct.
Lastly, one conceptual note: First, you aren't "creating an object of class Singleton" -- that's the whole point of a Singleton. :) You're just getting a reference to the existing object.

This one:
Singleton singleton = Singleton.getInstance();
should work. This is how you call static methods in Java. And the getInstance() method is declared as static. Are you sure you are using the very same Singleton class? Or maybe you have imported a class called the same in some other package.

since the constructor is private, it does not make sense to create an object using the constructor.
you should be using public static Singleton getInstance(), but the implementation is not very correct.
if (instance == null) {
instance = new Singleton();
}
return instance;
This is how you should be doing it. This ensure that it creates the instance if it does not exist, or simply returns the existing instance. Your code would also do the same thing, but this add to the readability.

Since we doesn't want to allow more than one copy to be accessed. So We need to manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one).
Thats why is
Singleton singleton = Singleton.getInstance();
Correct way to access any singletonObject.

There is nothing wrong in using
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context
This is the way to get the singleton object form the class. There must me something else. Please post some more details

It is still possible to create more than one instance of the class, as follows:
Singleton.getInstance().clone()

since getInstance() method is "static" and instance field too, yo can use Singleton.getInstance(); Without creating new exeple of class. Thihs is the poit of singletone

Related

Benefit of interface for getInstance call? [duplicate]

Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?
Simple declaration of instance as static field:
class Singleton
{
private static Singleton instance=new Singleton();
private Singleton () {..}
public static Singleton getInstance()
{
return instance;
}
}
vs
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
private Singleton () {..}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I ask this because Brian Goetz recommends the 1st approach in this article:
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
while he suggests the latter in this article
http://www.ibm.com/developerworks/library/j-jtp03304/
Does the latter approach provide any benefits that the former doesn't?
Well what i can say These articles are 7-9 years old.
Now we have > Java 1.5 where we have power of enumeration enum. According to 'Josh Block' The best way to write a singleton is to write a Single Element enum
public enum MySingleton{
Singleton;
// rest of the implementation.
// ....
}
But for your question I guess there is no issue in using either of the implementations. I personaly prefer the first option because its straightforward, simple to understand.
But watch out for the loop holes that we can be able to create more objects of these class in the same JVM at the same time by serializing and deserializing the object or by making the clone of the object.
Also make the class final, because we can violate the singleton by extending the class.
In first approach your singleton will get created once you load Singleton class. In the other, it will get created once you call getInstance() method. Singleton class may have many reasons to get loaded before you call getInstance. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.
The simple declaration pattern constructs the singleton when when the class Singleton is loaded. The initialize-on-demand idiom constructs the singleton when Singeton.getInstance() is called -- i.e., when class SingetonHolder is loaded.
So these are the same except for time; the second option allows you delay initialization. When to choose one or the other depends on (among other things) how much work you are doing in Singleton's constructor. If it's a lot, you may see improved application startup time with initialization-on-demand.
That said, my advice is to try not to do too much there so that the simplest pattern works for you.
-dg

java, as flliows,why does this global varaible of the program keep only an instance?

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.

No need to lazy init since the class has no state

In my java learning journey, I came across code that is commented with the following:
/**
* Singleton instance - no need to lazy init as the class holds no state.
*/
public static final SuperParentMarshaller instance = new SuperParentMarshaller ();
What does this mean? What kind of class would this be? It's purpose?
Thank you in advance.
This is eager initialization what you have mentioned. The object is already initialized before the request to this object. To make it lazy means the object will be initialize on it's first call. This is a single design pattern. There will be only oneobject of this class in the entire application.
// eager loading of INSTANCE
public class Singleton
{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
Lazy Initialization is :
// lazy initialization
public class Singleton
{
//initailzed during class loading
private static final Singleton INSTANCE;
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
// object will be initialized on it's first call.
if(INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
}
A singleton is to ensure there is one, and only ONE instance of that object present in your application. It can come in handy when for example to ensure there is only ONE audio class instance, so there can't be two instances asking the audio device to play two different things.
Though in practise, a singleton isn't used that much, it is handy to know it exists if you do ever come across the need of one.
The initialization method is than used to ensure only ONE instance can be created. There are several ways of ensuring this, if you DO NOT protect the instance from being created more than once, 2 threads could enter the class at the same time and you could end up with two instances of this class. Which would go against what you are trying to achieve.
Take a look at this: http://en.wikipedia.org/wiki/Singleton_pattern

Why a static singleton is a simple and elegant solution to avoid 'DCL'?

When need a singleton, is a static field a elegant solution?
class HelperSingleton {
static Helper singleton = new Helper();
public static Helper getInstance() {
return singleton;
}
}
When two threads access to getInstance at the same time, is there a chance the field singleton is not initialized completely? Or see the default values for fields of the helper object, rather than the values set in the constructor?
Static singleton is also lazy initialization?
I mean,
static Helper singleton = new Helper();
is this assigment atomic? And won't return default values ?
1) When a thread accesses static getInstance the first time class loader has to load the HelperSingleton class and it will lock other thread before class is loaded. So there is an implicit synchronization present. J.Bloch "Effective Java" Item 71 modern VM will synchronize field access only to initialize the class. Once the class is initialized, the VM will patch the code so that subsequent access to the field does not involve any testing or synchronization.
2) Your singleon is lazy, because there is only one access point - getInstance. Not only instance is created on demand but the whole class is loaded on demand. A class will not be initialized
until it is used [JLS, 12.4.1].
I think that the most elegant solution for a singleton is this:
public enum Singleton {
INSTANCE;
public Singleton getInstance() {
return INSTANCE;
}
}
Using the singleton pattern is somewhat problematic because sometimes you don't know that you really only have just one of them. Consider the case for example when you are using class loaders.
This question (and others) has a thorough explanation by the way.
Take a look at http://en.wikipedia.org/wiki/Singleton_pattern
There are a number of styles available explaining the good/bad.
If it were this :
class HelperSingleton {
static Helper singleton = null;
public static Helper getInstance() {
if(singleton == null) {
singleton = new Helper();
}
return singleton;
}
}
There could be a possibility here :
Thread 1 calls the getInstance() method and determines that singleton is null.
Thread 1 enters the if block, but is preempted by Thread 2 before creating a new instance.
Thread 2 calls the getInstance() method and determines that instance is null.
Thread 2 enters the if block and creates a new Helper object and assigns the variable singleton to this new object.
Thread 2 returns the Singleton object reference.
Thread 2 is preempted by Thread 1.
Thread 1 starts where it left off and executessingleton = new Helper(); which results in another Singleton object being created.
Thread 1 returns this object.
So we end up with two instances. Best way to create Singletons are using enum as answered here.
static Helper singleton = new Helper();
Here a new instance of Helper is created when the class is loaded and singleton holds the reference to that instance. You can get the detailed initialization process in JLS 12.4.2.

singleton and public static variable Java

I have 2 options:
Singleton Pattern
class Singleton{
private static Singleton singleton = null;
public static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
using a static final field
private static final Singleton singleton = new Singleton();
public static Singleton getSingleton() {
return singleton;
}
Whats the difference? (singlethreaded or multithreaded)
Updates: I am aware of Bill Pugh or enum method.
I am not looking for the correct way, but I have only used 1. Is there really any difference b/w 1 or 2?
The main difference is that with the first option , the singleton will only be initialised when getInstance is called, whereas with the second option, it will get initialized as soon as the containing class is loaded.
A third (preferred) option which is lazy and thread safe is to use an enum:
public enum Singleton {
INSTANCE;
}
There is one difference:
Solution 1 is a lazy initialization, the singleton instance will be created on the first invoke of getInstance
Solution 2 is a eager initialization, the singleton instance will be create when the class loades
They both are thread safe, calling the second one multi threaded is a little misleading
The 1st solutions appears to be lazier, but actually not.
A class is initialized when a static method/field is accessed for the 1st time.
It's likely that getInstance() is the only publicly accessible static method/field of the class. That's the point of singleton.
Then the class is initialized when someone calls getInstance() for the 1st time. That means the two solutions are essentially the same in laziness.
Of course, the 2nd solutions looks better and performs better.
So, with the update both options above are thread-safe. However the synchronized option requires each thread that calls instance to acquire this lock thereby reducing performance if this is done a lot. Also, using synchronized at the method level has the potential issue of using a publicly available lock (the class itself) that therefore if some thread acquires this lock (which it could) you could end up with deadlock. The static final option is more performant but does not do lazy initialization of the singleton (which might not be an issue depending on the system).
Another option that allows thread-safe lazy init of the Singleton is as follows:
public class MySingleton{
private static class Builder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton instance(){
return Builder.intance;
}
}
This works because the static inner class is guarenteed to be initialized before any method in the containing class is executed.

Categories

Resources