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
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.
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.
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.
The wikipedia article on Singletons mentions a few thread safe ways to implement the structure in Java. For my questions, let's consider Singletons that have lengthy initialization procedures and are acccessed by many threads at once.
Firstly, is this unmentioned method thread-safe, and if so, what does it synchronize on?
public class Singleton {
private Singleton instance;
private Singleton() {
//lots of initialization code
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Secondly, why is the following implementation thread safe AND lazy in initialization? What exactly happens if two threads enter the getInstance() method at the same time?
public class Singleton {
private Singleton() {
//lots of initialization code
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Finally, in the second example, what if one thread gets an instance first and another thread gets an instance and tries to perform actions on it before the constructor has finished in the first thread? Can you get into an unsafe state then?
Answer 1: static synchronized methods use the class object as the lock - ie in this case Singleton.class.
Answer 2: The java language, among other things:
loads classes when they are first accessed/used
guarantees that before access to a class is allowed, all static initializers have completed
These two facts mean that the inner static class SingletonHolder is not loaded until the getInstance() method is called. At that moment, and before the thread making the call is given access to it, the static instance of that class is instantiated as part of class loading.
This all means we have safe lazy loading, and without any need for synchronization/locks!
This pattern is the pattern to use for singletons. It beats other patterns because MyClass.getInstance() is the defacto industry standard for singletons - everyone who uses it automatically knows that they are dealing with a singleton (with code, it's always good to be obvious), so this pattern has the right API and the right implementation under the hood.
btw Bill Pugh's article is worth reading for completeness when understanding singleton patterns.
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