How do you implement singleton pattern




















The ability to create an independent instance when you need it is rather priceless in itself. Show 23 more comments. Depending on the usage, there are several "correct" answers. Peter Mortensen 29k 21 21 gold badges 97 97 silver badges bronze badges.

Roel Spilker Roel Spilker The check for reflection is useless. If other code is using reflection on privates, it's Game Over. There's no reason to even try to function correctly under such misuse.

And if you try, it will be an incomplete "protection" anyways, just a lot of wasted code. Could someone elaborate on this please? The deserialisation protection is completely broken I think this is mentioned in Effective Java 2nd Ed. Look at Jonathan's answer for the actually most simple solution that is sufficient in This is useful when your singleton needs to inherit from a superclass. You cannot use the enum singleton pattern in this case, since enums cannot have a superclass they can implement interfaces, though.

For example, Google Guava uses a static final field when the enum singleton pattern is not an option: code. Show 9 more comments. While implementing Singleton we have two options: Lazy loading Early loading Lazy loading adds bit overhead lots of to be honest , so use it only when you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.

For details: The "Double-Checked Locking is Broken" Declaration Now we are sure about evil threads, but what about the cruel serialization? And we have come so far. Ajinkya Ajinkya Just a clarification: singletons implemented using enum are initialized lazily. Details here: stackoverflow. One of the best answers I have ever red on stackoverflow. There is a serialization problem with using enums as a singleton: Any member field values are not serialized and therefore not restored.

See Java Object Serialization Specification, version 6. Third problem: No customization: Any class-specific writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods defined by enum types are ignored during serialization and deserialization. Show 4 more comments. Benno Richters Benno Richters Fair enough! I'm just comfortable with volatile and it's use. Oh, and three cheers for JCiP. Oh, this is apparently the approach advocated by William Pugh, of FindBugz fame.

Stu The first edition of Effective Java copyright details this pattern under item Bno: What about making constructor private? AlikElzin-kilaka Not quite. The instance is created in the class loading phase for BarHolder , which is delayed until the first time it's needed. Bar's constructor can be as complicated as you want, but it won't get called until the first getBar.

And if getBar is called "too early" then you'll face the same problem no matter how singleons are implemented. You can see the lazy class loading of the code above here: pastebin. Show 1 more comment. Stu Thompson Stu Thompson Where can I learn more about the volatile modifier? See comments of stackoverflow. I think it is important to mention about reflection attacks. True that most developers don't need to worry about, but it seems that examples like these over Enum-based singletons should include either code that protects against multiple-instantiation attacks or simply put a disclaimer indicating such possibilities.

Volatile keyword is not needed here - as synchronization gives both mutual exclusion plus memory visibility. My understanding is that the enum approach provides both thread safety and lazy initialization. It is also much simpler Furthermore, if you want to avoid an enum, I'd still prevent the nested static class approach Show 6 more comments.

Jonathan Jonathan 7, 5 5 gold badges 27 27 silver badges 35 35 bronze badges. That effectively is lazy initialisation, since the static singleton won't be instantiated until the class is loaded and the class won't be loaded until it's needed which will be right about the time that you first reference the getInstance method.

If class A does get loaded way before you want the static to be instantiated, you can wrap the static in a static inner class to decouple the class initialisation. No other thread will get access to the class while the static members are initialized. This approach have one limitation: The constructor cannot throw a exception.

Show 7 more comments. Neil Burroughs Neil Burroughs 3 3 silver badges 3 3 bronze badges. So my answer to the OP would be in all but the most trivial sample code to: Use a DI framework like Spring Framework , then Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.

Andrew Swan Andrew Swan Perhaps because people disagree with you. I haven't downvoted you, but i do disagree: i think DI can be used to solve the same problems singletons are. This is based on understanding "singleton" to mean "an object with a single instance which is accessed directly by a global name", rather than just "an object with a single instance", which is perhaps slightly tricksy. And it becomes somebody else's problem to call that constructor. A DI framework would do it with a global map of some sort; a handbuilt DI architecture would do it because the app's main method or one of its minions would create the dependency and then call the constructor.

Essentially, the use of a global variable or a global method is just a simple form of the dreaded service locator pattern , and can be replaced with dependency injection, just like any other use of that pattern. TomAnderson I'm really confused as to why people 'dread' the service locator pattern. I think in most cases it's overkill or not needed at best, however, there are seemingly useful cases. Saying the code isn't structured isn't a valid argument, because sometimes groupings of parameters just doesn't make sense.

Also, from a unit testing perspective, I don't care about testing the service, just the business logic of it, and if it's coded right, then this would be easy. I only seen this need in very large scale projects. Aidos Aidos. It is more of a foundational class that kick-starts the rest of your application and if it were duplicated you will end up with a complete chaos i.

Passing global data all over your application is a big coupling red flag. Use it when you acknowledge you really need it. Abhijit Gaikwad Abhijit Gaikwad 2, 26 26 silver badges 37 37 bronze badges. Matt Matt 2, 15 15 silver badges 18 18 bronze badges. Michael Andrews Michael Andrews 7 7 silver badges 13 13 bronze badges.

Could you please explain why BearerToken instance in your article isn't static? And what is it result. This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:. As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it?

Well, static constructors in C are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples.

There are a couple of wrinkles, however:. One shortcut you can take with this implementation and only this one is to just make instance a public static readonly variable, and get rid of the property entirely.

This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. Note that the static constructor itself is still required if you require laziness. Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones.

Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private.

The code is a bit more complicated in order to make the instantiation lazy, however. If you're using.

NET 4 or higher , you can use the System. 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. 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. Depending on your requirements, you may wish to experiment with other modes. In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above.

This can increase performance as it allows the JIT compiler to make a single check for instance at the start of a method to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a relatively significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. A lot of the reason for this page's existence is people trying to be clever, and thus coming up with the double-checked locking algorithm.

There is an attitude of locking being expensive which is common and misguided. Untill now, we have solved both of the problems of synchronization and serialization.

Now, we are just one step away from a correct and complete implementation. The only missing part is a serial version id. This is required in cases where your class structure changes between serialization and deserialization.

A changed class structure will cause the JVM to give an exception in the de-serializing process. This problem can be solved only by adding a unique serial version id to the class. It will prevent the compiler from throwing the exception by telling it that both classes are same, and will load the available instance variables only. After having discussed so many possible approaches and other possible error cases, I will recommend to you the code template below, to design your singleton class which shall ensure only one instance of a class in the whole application in all above discussed scenarios.

I hope this post has enough information to help make you understand the most common approaches for the singleton pattern and singleton best practices. Let me know your thoughts. Realtime Singleton Examples — I just thought to add some examples which can be referred for further study and mention in interviews:. Subscribe to get new post notifications, industry updates, best practices, and much more.

Directly into your inbox, for free. Hi Lokesh, I would want to know the practical usage of readResolve method. When i serialize an object , while deserializing i expect to get the content that was serialized. With the ReadResolve method, if i return the existing singleton instance i end up returning the existing instance and i will not get the values that were actually serialized.

I am not able to get the intent of ReadResolve method. Will the Bill Pugh solution work in case of multiple threads? As mentioned in the Drawback of singleton with Lazy case. What will happen if multiple threads try to get the instance of the singleton class.

Yes it does. JVM will ensure sequential initialization of the static classes. Hi Lokesh, I was asked in an Interview that you are creating private constructor so that you can not access the class from outside, then why we are declaring the object refernce variable private static volatile EagerSingleton instance as private.

I understood that deserialization creates another instance of Singleton. But Why? On what instance does readResolve method is invoked when the deserialized instance is a different instance altogether? As per you recommend above code template to design singleton class. But how Thread safety achieve in above code?? Static initialization is performed once per class-loader and JVM ensures the single copy of static fields. So even if two threads access above code, only one instance of class will be created by JVM.

Hi Lokesh! Will you please elaborate it and explain it with any example? Hi Lokesh sir, Nice post i am very good clearity abouth Singleton class but i am confused readResolve method please explain me which class declare the readResolve method and who will call?

The class which you are making singleton will declare readResolve method. You do not need to call it in any class, JVM internally uses this method. Hi Lokesh, I am leave here my singleton code please say me is all angle correct or not… package com. In final example, why dont you declare variable as volatile. How your final solution will work in multithreaded enviornment.

Hi lokesh , can you plese explain why you are going to synchronize the object in lazy initialization case. Every thing you have written in this post is excellent. I have some doubts. Please clarify it.

Singleton means only one instance of class with in a jvm. There is two web application wants to use same singletone class. But whenever , web application uses this singleton class it creates one instance for an application means per application one instnace. But my web application runs under jvm with same server. Hi Lokesh, Thanks for the nice explanation. I have one query- how can we ensure or use singelton behaviour in clustered environment?

Solution is correct but enums are best where they may fit in. I was asked in an interview to Create singleton class using public constructor. Thanks in advance. Please share your thoughts. You made valid argument. It will definitely cut-down at least lines of code needed to initialize the object. BUT, when application is running and there are N threads which want to check if object is null or not; then N-1 will be blocked because null check is in synchronized block.

Hi Lokesh, Your way of converting difficult topic to easier is remarkable. I again read the section of lazy initialization. It is correctly written. Any reason why you think so? Hi Lokesh Sir, i am new in java and tryning to make a slideshow in my project. I have 2 option 1st using JavaScript and 2nd using widget. Great article, thanks! BTW, is it a good idea to use the singleton for a configuration object which can be changed after creation?

There is one typo that I have observed. While explaining double-checked locking , you are referring to class name as EagerSingleton but it is lazy singleton. I would be more clear if you make the name LazySingleton. Nice article… i was looking for this concept with multiple doubts. My all doubts are cleared by reading all these comments. Bill pugh solution does. Anyway, java enums are converted to classes only with additional methods e. Hi Lokesh, Thanks for writing such a good informative blog.

But i had one doubt on singleton. But when application is running production clustered environment with multiple instances of JVM running can break the singleton behavior of the class? You are right.. In clustered deployment, there exist multiple instances of singleton.

You are right, singleton is one per JVM. Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide. Load Comments. What's New. Most popular in Design Pattern. Most visited in Java. We use cookies to ensure you have the best browsing experience on our website.



0コメント

  • 1000 / 1000