- Practice
- Java
- Advanced
- Java Singleton Pattern
- Discussions
Java Singleton Pattern
Java Singleton Pattern
Jason_Yao_NYU + 9 comments Just saying that from a completeness point of view, something like this would be required:
class Singleton { private volatile static Singleton instance; public static String str; private Singleton() {} static Singleton getSingleInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
This utilizes the "double-checked locking" design pattern, and guarentees the following for the singleton:
- Lazy initialization (great for resource allocation, and means we don't waste resources with eager initialization)
- No race condition for lazy initialization (two+ more threads each trying to create a singleton will fail, guarenteed by syncronized)
- Acquiring a lock (expensive operation) is done once and only once, thus there is no performance penalty
- Only allows the singleton to be used when it is fully instantiated (thanks to the
volatile
keyword there)
An even more clever way is this:
class Singleton{ private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
The second way still retains all the requirements from the first, and is just more concise. (technically speaking it's a form of lazy initialization, since it eagerly initializes on demand).
More reading available here: cs.nyu.edu/courses/fall16/CSCI-UA.0470-001/slides/lecture25.pdf#page=52.
qxzsilver + 0 comments Great link and helpful info
kata_lune + 1 comment What for do you need additional inner holder class? You already has laze initialisation with this:
class Singleton{ private Singleton() {} private static final Singleton INSTANCE = new Singleton(); public static Singleton getInstance() { return INSTANCE; } }
Jason_Yao_NYU + 3 comments Hey! Actually the code you posted is an example of eager initialization[1], and not lazy initialization- you'd want to avoid this since if the initialization cost is high, and if you end up not using the Singleton, it would be a waste of resources.
As for why the SingletonHolder, it's the use of an idiomatic design pattern, which Wikipedia can explain in more detail if you'd like to learn more[2].
[1] http://cs.nyu.edu/courses/fall16/CSCI-UA.0470-001/slides/lecture25.pdf#page=52
[2] https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
kata_lune + 0 comments Thanks for the link! I didn't know that only inner classes are not loaded until they are referenced, I thought any class is not loaded until it is referenced.
kata_lune + 0 comments I have only noticed, that in the example of inner class in the first document - the static nested class (not inner class) is presented. Does this mean that all nested classed (not inners only) are not loaded until referenced?
mar87 + 0 comments Thanks for share link!
themast3r + 0 comments Was so happy about my naive approach:
class Singleton { public String str; private static Singleton singleton; private Singleton() {} public static getSingleInstance() { if(singleton == null) { singleton = new Singleton(); } return singleton; } }
came here and learned something useful and new. Thanks a ton man.
johnwill4g + 0 comments where should we identify the public str here? public static String str="";
kapploneon + 1 comment I am not sure why but the second method is throwing me Exception in thread "main" java.lang.AssertionError at Main.main(Main.java:34)
kapploneon + 1 comment Here is what I tested:
class Singleton{ public static String str; private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getSingleInstance() { return SingletonHolder.INSTANCE; } }
kbkr_24794 + 0 comments why don't you try making the static variable "str" to an instance variable in your code.
public static String str; ==> public String str;
andresp + 0 comments That's not for "completeness" but for "thread-safety", which is not a requirement of the problem.
There are several other challenges here at HackerRank for which their accepted solutions would break in a concurrent environment.
Nevertheless, it's great to mention this, therefore the thumbs up.
Vaeth + 0 comments How does this fulfill the requirement of multi-threading/eliminating the race conditions? Is there some intrinsic lock in the final keyword I never knew about?
Vaeth + 0 comments Also would like to point out whatever secret tests they run, this implementation does not work. Not exactly sure why, an assertion error of some sort
nireekshap1996 + 0 comments In first code why have you taken String variable
dvt32 + 4 comments Java 8 (make sure to NOT remove the import statements foolishly like me or you will get errors):
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.reflect.*; class Singleton { private Singleton() {} public String str; private static Singleton instance = new Singleton(); public static Singleton getSingleInstance() { return instance; } }
srisushk + 1 comment Why does not it work when I just write return new Singleton(); directly inside getSingleInstance() ?
dvt32 + 1 comment Because when you call getSingleInstance(), it will return a new object every time. In other words, you can make an unlimited number of objects with that method.
By making a private object (in this case, the object "instance"), your function doesn't return a new object each time - it returns the only Singleton object available, which is "instance" and you can't make any more objects from the Singleton class (which is exactly the idea behind the Singleton pattern).I hope this cleared up any confusion.
reve99 + 1 comment static is the main concern here .., not private
shaikhaziz11 + 0 comments yes u are right it is beacause of static we save a lot of memory
Ignis_Qui_Vir + 0 comments [deleted]RodneyShag + 0 comments The only 2 import statements you need are
import java.util.Scanner; import java.lang.reflect.Constructor;
themast3r + 0 comments That's a bad coding practise. First it is an Eager Initializtion and second you did not perform a Double Checked Locking. See Jason_Yao_NYU's comment.
tao_zhang + 2 comments Mine
class Singleton{ public String str; private static Singleton instance = null; private Singleton(){ } public static Singleton getSingleInstance(){ if (instance==null) instance = new Singleton(); return instance; } }
Ziltoid125 + 1 comment Does your solution pass the tests?
tao_zhang + 1 comment Yes.
rishikamaroo + 1 comment Can you please explain why did you use
.....if(instance==null).... conditiontao_zhang + 2 comments if instance exists, you don't need to create another one, just use the current instance, that's the point of singleton ---- only create a new instance when there is NO instance at all
rishikamaroo + 0 comments okh thanks
maximshen + 1 comment IMHO, @dvt32's solution is the best. You can avoid checking "instance == null" and meanwhile create a thread safe Singleton instance during class loading. Alternatively, you can still use lazy initialization thread safe Singleton, using synchronized. Find more from my post
class Singleton { private Singleton() {} public String str; private static final Singleton instance = new Singleton(); public static Singleton getSingleInstance() { return instance; } }
xplt_ + 1 comment This one lacks of final modifier for the "instance" field (your blog post is correct [BTW, the link is a bit broken], this example [and @dvt32's code]) - isn't).
maximshen + 1 comment Good catch ! I don't think it matters for private variable here, but for good practice, 'final' should be added.
xplt_ + 1 comment Relevant: question about the final modifier on Stack Overflow
qanmberabbas5121 + 0 comments
ivanbessonov + 4 comments Guys, why did my solution with static holder class had some weird assertion? It's definetely the best singleton implementation for Java:
class Singleton { private Singleton() {} public static Singleton getInstance() { return SingletonHolder.INSTANCE; } private static class SingletonHolder { public static final Singleton INSTANCE = new Singleton(); } }
Disruption + 1 comment That's the same one I use, and I also get an assertion error :(
lozb0912 + 0 comments I have same error. why?
atreides + 1 comment Not quite 'the best' if you think of synchronization + serialization: http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples . Maybe enum could win some more points.
(but this pattern should be avoided as much as possible)
ivanbessonov + 1 comment I don't see any problem with synchronization, everything's correct here.
| "The problem with above serialized singleton class is that whenever we deserialize it, it will create a new instance of the class" - this is universal problem, one should not serialize singleton with default serializer :)EDIT: readResolve() looks like a dirty workaround, but it really should work!
atreides + 1 comment true... but a sort of || class loaders could harm :)
ivanbessonov + 0 comments || class loaders will handle it, because they synchronize class loading inside of jvm. Nothing to worry about
atreides + 1 comment I think you forgot that str instance string. See the requirements. That's something they use to test this. IDK how.
ivanbessonov + 0 comments I avoided str instance for purpose, because I didn't want to spoil whole solution
ahmad_elyaszada + 0 comments Aggreed
Devishwash + 0 comments Here is My'Solution
class Singleton{ public String str; static Singleton s= new Singleton(); private Singleton(){ } public static Singleton getSingleInstance(){ return s; } }
iamvisshu + 0 comments Solution :)
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.reflect.*; class Singleton { public String str; private static Singleton singleton; private Singleton() {} public static Singleton getSingleInstance() { if(singleton == null) { singleton = new Singleton(); } return singleton; } }
18dcs024 + 0 comments I am writing the correct code for the java program .The code is correct and passes all the test cases...
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.reflect.*; class Singleton{ public String str; private static Singleton singleton; private Singleton() {} public static Singleton getSingleInstance() { if(singleton == null) { singleton = new Singleton(); } return singleton; } }
siddharth_nawani + 0 comments public String str; public static Singleton singleton = null; private Singleton() { } static Singleton getSingleInstance() { if (singleton == null) singleton = new Singleton(); return singleton; }
Harioom + 0 comments class Singleton{ public static Singleton instance; public String str; private Singleton(){ str = "Hello I am a singleton! Let me say hello world to you"; } public static Singleton getSingleInstance(){ if(instance==null){ instance=new Singleton(); } return instance; } } class Test{ public static void main(String args){ Singleton singleton=Singleton.getSingleInstance(); System.out.println(singleton.str); } }
benbasty + 0 comments class Singleton{ private Singleton() {} public String str; private static final Singleton instance = new Singleton(); public static Singleton getSingleInstance() { return instance; } }
Sort 73 Discussions, By:
Please Login in order to post a comment