I am sure that everyone knows the following implementation of Singleton pattern:
public class Singleton {
private static volatile Singleton instance;
private Singleton(){}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.instance){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}}
I know that it is an implementation accordingly to lazy initialization.
But Java ClassLoader loads classes in a lazy mode.
How is it possible for any object to be not lazily initialized?
Regardless an object realization an instance is created only when you use word 'new' or call a factory method.
What is non-lazily class loading?
Non-lazy loading would instantiate instance immediately when the class is loaded, rather than waiting until the first call to getInstance().
public class Singleton {
private static volatile Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
If the class is loaded but nobody ever calls getInstance() it wastes time and memory creating an object that is never used.
Related
In singleton design pattern, we restrict creation of objects to a single object using private constructor.
To provide a global handle to it, we use a "public static" method.
My question is why static is needed here? Why not just public?
Short answer:
Assume you have a Singleton class:
public class Singleton {
...
}
Then the constructor is probably private which means you cannot use new Singleton() from another class.
So the only way to access something that is inside the Singleton class would be using Singleton.methodName() or Singleton.fieldName.
But in order to do this then these methods and fields cannot be part of an object, they have to be static. And the getSingleton() or getInstance() method is no exception.
Answer with examples:
Assume you have a Singleton class:
public class Singleton {
}
We can now add the constructor. But it can not be public, since if it is public then you can just use new Singleton() from every other class and then it would not be a Singleton anymore. So the class would now look like this.
public class Singleton {
private Singleton(){
}
}
Now that the constructor is private this means that you cannot instantiate the class from another class it can also be instantiated from inside the Singleton class. So we should add the getInstance() or getSingleton() method.
public class Singleton {
private Singleton(){
}
public Singleton getSingleton(){
return null;
}
}
But now we cannot access it since the getSingleton() method can only be used on an object and we cannot instantiate a Singleton object from outside the class. So the getSingleton() needs to be accessed by using Singleton.getSingleton() and therefore it has to become a static method.
public class Singleton {
private Singleton(){
}
public static Singleton getSingleton(){
return null;
}
}
The answer so far should answer the question but it is not a functional Singleton class. So please continue reading for the complete answer.
Now we also want to return the instance of the Singleton from the getSingleton() method. So we also want a field called instance of singleton to point to the instance of the Singleton class.
public class Singleton {
private Singleton instance;
private Singleton(){
}
public static Singleton getSingleton(){
return instance;
}
}
But now the instance field is not accessible by the get getSingleton() method since the way the class is written right now the instance is a field of an the object and not the class, so the instance field has to become static as well.
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getSingleton(){
return instance;
}
}
And now the final problem is that the variable instance is not instantiated anywhere so it will always return null. So we have to check in the getSingleton() that if the instance is null then create a new Singleton() and make the instance field point to it.
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getSingleton(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
If you want a thread safe Singleton class you can use something like this instead (suggested by Boris the Spider):
public enum Singleton {
INSTANCE;
private Singleton(){
// TODO
}
}
And now the Singleton is complete.
If the method is public and no static you will need an instance of the class to be able to call that method.. that makes no sense.
static method instead can be invoked with no instance since they belong the class
I have code like this:
class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
System.out.println("Singleton constructed.");
}
public static Singleton getInstance() {
return INSTANCE;
}
}
When we don't have any other static method that getInstance, is this singleton lazy initializated? As far as I know class is initialized only in some cases, like:
An Instance of class is created using either new() keyword or using
reflection using class.forName(), which may throw
ClassNotFoundException in Java.
An static method of Class is invoked.
An static field of Class is assigned.
An static field of class is used which is not a constant variable.
If Class is a top level class and an assert statement lexically nested within class is executed.
(Surce: http://javarevisited.blogspot.com/2012/07/when-class-loading-initialization-java-example.html#ixzz4IjIe2Rf5)
So when the only static method is getInstance and constructor is private there is no possibility to initialize Singleton class in any other way than using getInstance method (apart from reflection). So the object is created only when we need it so it's a lazy initialization, right? Or maybe I missed something?
You mentioned static methods and private constructor. Add another static field, something like:
static int NUMBER = 13;
in your Singleton class. And in the main method of other class:
System.out.println(Singleton.NUMBER);
then, you will see that your Singleton is not lazy initialized.
BUT, when your field is static FINAL:
static final int NUMBER = 13;
the Singleton is lazy initialized.
What is more, when you add static and non-static initialization blocks in your Singleton class:
{
System.out.println("non-static");
}
static {
System.out.println("static");
}
the order is: non-static, private constructor and then static, because you are instatiating an object as a value of static field. So, it is very tricky :)
In summary, in some cases your Singleton may be considered as lazy initialized but it is not in general.
It's initialized immediately so no, it's not. Typically a lazy initialization means you initialize it when you try to actually retrieve it but the field isn't initialized yet.
Lazy initialization is not about the class initializing -- it's about the field that's contained in it. In your case as soon as the class is loaded, the field will be initialized immediately.
Your example adapted to use lazy initialization:
class Singleton {
private static Singleton INSTANCE;
private Singleton() {
System.out.println("Singleton constructed.");
}
public static Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
This will only construct the singleton when it is actually requested and not just when the Singleton class is loaded in memory. In your situation, if it is loaded in memory then its static fields would be initialized (including your singleton field).
EDIT: I was wrong. A class is NOT loaded just by referencing it, like below:
System.out.println(Singleton.class);
A class is loaded by the class loader as soon as an instance is created, a static member is referenced, or by loading it programmatically:
Class<?> clazz = Class.forName("Singleton"); // fully qualified classname
The above statement causes the class to be loaded, and all static members and blocks will be processed in order of appearance in the class. In your example class this will cause the INSTANCE variable to be initialized (and the message to be printed to System.out). This proves that your approach does not guarantee lazy loading.
A better way to implement a lazy loading singleton is with the Singleton holder pattern:
class Singleton {
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
// hide constructor
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
No, it is not lazy initialized.
Lazy mean on first call or never. In your case it is not on first call.
You can pass lazy initialization problem to SingletonHolder class. It will be initialized on first getInstance call.
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
If you're using .NET 4 (or higher), John Skeet recommends you do the following:
You can use the System.Lazy type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton> (() => new
Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.
The code above implicitly uses LazyThreadSafetyMode.ExecutionAndPublication as the thread safety mode for the Lazy. Depending on your requirements, you may wish to experiment with other modes.
Below are two ways to implement a singleton. What are the advantages and disadvantages of each?
Static initialization:
class Singleton {
private Singleton instance;
static {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}
Lazy initialization is:
class Singleton {
private Singleton instance;
public Singleton getInstance(){
if (instance == null) instance = new Singleton();
return instance;
}
}
Synchronized Accessor
public class Singleton {
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
lazy load
low perfomance
Double Checked Locking & volatile
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
Singleton localInstance = instance;
if (localInstance == null) {
synchronized (Singleton.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Singleton();
}
}
}
return localInstance;
}
}
lazy load
high perfomance
JDK should be 1,5 ++
On Demand Holder idiom
public class Singleton {
public static class SingletonHolder {
public static final Singleton HOLDER_INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.HOLDER_INSTANCE;
}
}
lazy load
high performance
cant be used for non static class fields
First one is eager initialisation.
eager initialization creates the instance even before it’s being used and that is not the best practice to use.
Second one is Lazy Initialization.
Lazy implementation works fine incase of single threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if loop at the same time. It will destroy the singleton pattern and both threads will get the different instances of singleton class.
Please visit: http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples#static-block-initialization for more information
NOTE: static blocks can access only static variables defined outside static block directly. The object you want to restrict to only one instance creation should be static. Your first methods fails during compilation, second method requires you to create the object first Follow this approach:
class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton getInstance()
{
if(instance == null)
instance = new Singleton();
return instance;
}
}
Ensure no creation of the object elsewhere, so change the constructor to private
make your class like this
public class Singleton {
private Singleton() {
}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
and call it like..
Singleton instance = Singleton.getInstance();
Static initializers cannot throw exceptions and absorb RuntimeExceptions into ClassDefNotFoundException, which does not halt execution. So you could see lots of
ClassDefNotFoundException's in your logs and you might not even realize something is wrong until much later because execution continues.
The 2nd method allows RuntimeExceptions to stop execution.
More details here:
https://twasink.net/2006/07/07/how-not-to-handle-exceptions-from-static-code-block-in-java/
Use static static block if you need some things to be initliazedz when the app starts. In it's own. Like you may want to load some properties from some file and do something useful....etc
static {
instance = new Singleton();
loadStuff();
}
Use lazy initialization
class Singleton {
private Singleton instance;
public Singleton getInstance(){
if (instance == null) instance = new Singleton();
loadStuff()
return instance;
}
}
and loadStuff will only be triggered when the Singleton.getInstance() is first called.
I am not sure, if anyone has asked this question before (If so apologies).
code copied from wikipedia.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
How it is thread safe? is it(only) because there is no mutating state in this class?
what happens if I modify it like this
public class Singleton {
private static final Singleton instance = new Singleton();
private FancyClass obj1;
private FancyClass obj2;
//feel free to imagine all the getters and setters for obj1 and obj2,
// like getObj1() and so forth
//tricky method
public void doSomething() {
obj1.destroyEnemy();
obj2.destroyFriend();
}
private Singleton() {
obj1 = null;
obj2 = null;
}
public static Singleton getInstance() {
return instance;
}
}
I have no interest in design-patterns discussion, this is the kind of code, I am supposed to maintain. is the above 'singleton' thread safe, assuming that FancyClass is java standard library class.
You're right that the first example is safe only because there is no mutable state.
In the second example, the singleton isn't doing anything to make it threadsafe, whether it's safe depends on if FancyClass is threadsafe. Putting synchronized on the doSomething method would make it threadsafe.
Introducing getters and setters for obj1 and obj2 would also have the potential to create problems, those would have to be synchronized on the same lock as the doSomething method, and you would need locking even if FancyClass is threadsafe, because if different threads are changing things then those changes need to be made visible across threads.
The first code guarantees that all threads that call getInstance() get a reference to the same instance of Singleton.
For your implementation (second example), the same is true for obj1 and obj2, because they're created while the class itself is created and class creation is thread safe (can't be created twice/"in parallel" within the same classloader).
The doSomething() method is not thread safe. Make it synchronized if you need an atomic operation.
The Singleton pattern is not designed to be Thread Safe at all, just to be unique and forbidding creation of additional instances. The only part that is thread safe in you code is the Singleton instantiation private static final Singleton instance = new Singleton(); as it's invoked one time a class loading time.
But effectively, if there's no members in your class modified by a method invked concurently by external systems, your Singleton will be/stay ThreadSafe
About your code -
Since you are making your constructor private it will never be called. So declaring it null there makes no sense. Anyway instance variables are automatically assigned default values.
First of all the 1st code
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
is called Early initialization unlike lazy initialization in which you create instance only when needed. To make it thread safe you need to do the following
public class Singleton {
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
Example is of lazy initialization but the concept remains the same.
I have a singleton in singleton data structure. Currently my implementation is like below:
public class Singleton {
private Object embInstance;
private Singleton() {
embInstance = new Object();
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
public Object getEmbInstance() {
return embInstance;
}
public Object resetEmbInstance() {
embInstance = null;
}
}
My question are:
Does 'private Singleton()' have to be empty or is it OK to add some code in it?
Is this implementation thread-safe with respect to embInstance?
This implementation is not lazy-loading for embInstance. How to implement a thread-safe lazy-loading for embInstance?
Thanks!
it's ok to add some code to your private, no-args constructor.
I believe the SingletonHolder class will only be initialized once, therefore instance will be guaranteed to be assigned exactly once. However, within the Singleton class you have setters and getters that are not synchronized, so you may have some threading issues there wrt embInstance.
thread-safe lazy-loading: same as lazy-loading, but do it inside a synchronized block:
public static Object getInstance() {
if(embInstance == null) {
synchronized(Singleton.class) {
if(embInstance == null) {
embInstance = new Singleton();
}
}
}
return embInstance;
}
Note that this code is both efficient (no synchronization required once your data is initialized) and thread-safe (initialization occurs inside a synchronized block).
Hope that helps.
The synchronized keyword keeps the methods thread-safe. The getEmbInstance() is the standard way to do lazy instantiation.
public class Singleton {
private Object embInstance;
private Singleton() {
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
public synchronized Object getEmbInstance() {
if (embInstance == null)
embInstance = new Object();
return embInstance;
}
public synchronized Object resetEmbInstance() {
embInstance = null;
}
}
Not sure, what you mean. It is certainly syntactically acceptable to have code in the Singleton constructor
This is not inherently thread safe. If embInstance is accessed by multiple threads even if it is via getEmbInstance, it will suffer from race conditions. You must use synchronized to access it if you wish for threadsafety.
To implement a thread-safe lazy load, you must have a lock that prevents changes to Singleton. You can just use the instance of Singleton to lock it as such:
synchronized(this)
Also, you don't need SingletonHolder you can just have a public static Singleton instance in the Singleton class itself.
....eh ...isn't that overcomplexifying things? Why have a singleton in a singleton? Why so many classes?
Moreover, you have a method to 'reset' your singleton to null, but none to actually instantiate a new one.
Why not simply:
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton(); // The "lazy loading" :p
return instance;
}
}
public class A {
A a;
private A() {}
synchronized public static A getOb() {
if (a == null) {
a = new A();
}
return a;
}
}
You should use synchronized for thread-safety in Singleton.