We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Loading...
  • Practice
  • Compete
  • Jobs
  • Leaderboard
  • Hiring developers?
  1. Practice
  2. Java
  3. Advanced
  4. Java Singleton Pattern
  5. Discussions

Java Singleton Pattern

  • Problem
  • Submissions
  • Leaderboard
  • Discussions
  • Editorial

Sort 73 Discussions, By:

votes
  • recency
  • votes

Please Login in order to post a comment

  • Jason_Yao_NYU 3 years ago+ 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.

    46|
    Permalink
    • qxzsilver 3 years ago+ 0 comments

      Great link and helpful info

      0|
      ParentPermalink
    • kata_lune 2 years ago+ 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;
          }
      }
      
      0|
      ParentPermalink
      • Jason_Yao_NYU 2 years ago+ 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

        9|
        ParentPermalink
        • kata_lune 2 years ago+ 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.

          0|
          ParentPermalink
        • kata_lune 2 years ago+ 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?

          0|
          ParentPermalink
        • mar87 2 years ago+ 0 comments

          Thanks for share link!

          0|
          ParentPermalink
    • themast3r 2 years ago+ 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.

      1|
      ParentPermalink
    • johnwill4g 2 years ago+ 0 comments

      where should we identify the public str here? public static String str="";

      0|
      ParentPermalink
    • kapploneon 1 year ago+ 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)

      0|
      ParentPermalink
      • kapploneon 1 year ago+ 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;
                }
        }
        
        0|
        ParentPermalink
        • kbkr_24794 1 year ago+ 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;
          
          0|
          ParentPermalink
    • andresp 1 year ago+ 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.

      0|
      ParentPermalink
    • Vaeth 11 months ago+ 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?

      0|
      ParentPermalink
    • Vaeth 11 months ago+ 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

      0|
      ParentPermalink
    • nireekshap1996 7 months ago+ 0 comments

      In first code why have you taken String variable

      0|
      ParentPermalink
  • dvt32 3 years ago+ 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; }
    }
    
    8|
    Permalink
    • srisushk 3 years ago+ 1 comment

      Why does not it work when I just write return new Singleton(); directly inside getSingleInstance() ?

      1|
      ParentPermalink
      • dvt32 3 years ago+ 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.

        17|
        ParentPermalink
        • reve99 3 years ago+ 1 comment

          static is the main concern here .., not private

          6|
          ParentPermalink
          • shaikhaziz11 3 years ago+ 0 comments

            yes u are right it is beacause of static we save a lot of memory

            0|
            ParentPermalink
    • Ignis_Qui_Vir 3 years ago+ 0 comments
      [deleted]
      0|
      ParentPermalink
    • RodneyShag 3 years ago+ 0 comments

      The only 2 import statements you need are

      import java.util.Scanner;
      import java.lang.reflect.Constructor;
      

      HackerRank solutions.

      0|
      ParentPermalink
    • themast3r 2 years ago+ 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.

      0|
      ParentPermalink
  • tao_zhang 3 years ago+ 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;
        }
    }
    
    6|
    Permalink
    • Ziltoid125 3 years ago+ 1 comment

      Does your solution pass the tests?

      1|
      ParentPermalink
      • tao_zhang 3 years ago+ 1 comment

        Yes.

        0|
        ParentPermalink
        • rishikamaroo 3 years ago+ 1 comment

          Can you please explain why did you use
          .....if(instance==null).... condition

          0|
          ParentPermalink
          • tao_zhang 3 years ago+ 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

            2|
            ParentPermalink
            • rishikamaroo 3 years ago+ 0 comments

              okh thanks

              0|
              ParentPermalink
            • maximshen 3 years ago+ 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; 
                  }
              }        
              
              0|
              ParentPermalink
              • xplt_ 3 years ago+ 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).

                0|
                ParentPermalink
                • maximshen 3 years ago+ 1 comment

                  Good catch ! I don't think it matters for private variable here, but for good practice, 'final' should be added.

                  0|
                  ParentPermalink
                  • xplt_ 3 years ago+ 1 comment

                    Relevant: question about the final modifier on Stack Overflow

                    0|
                    ParentPermalink
                    • qanmberabbas5121 2 days ago+ 0 comments

                      Best Gaming Keyboard

                      0|
                      ParentPermalink
    • xplt_ 3 years ago+ 1 comment

      This is not thread-safe realization. This variant of Singleton needs "synchronized" mark for the "getSingleInstance()" method. See here

      1|
      ParentPermalink
      • tao_zhang 3 years ago+ 0 comments

        you are right, I forgot to do that

        0|
        ParentPermalink
  • ivanbessonov 3 years ago+ 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();
        }
    }
    
    2|
    Permalink
    • Disruption 3 years ago+ 1 comment

      That's the same one I use, and I also get an assertion error :(

      1|
      ParentPermalink
      • lozb0912 2 years ago+ 0 comments

        I have same error. why?

        0|
        ParentPermalink
    • atreides 3 years ago+ 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)

      0|
      ParentPermalink
      • ivanbessonov 3 years ago+ 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!

        0|
        ParentPermalink
        • atreides 3 years ago+ 1 comment

          true... but a sort of || class loaders could harm :)

          0|
          ParentPermalink
          • ivanbessonov 3 years ago+ 0 comments

            || class loaders will handle it, because they synchronize class loading inside of jvm. Nothing to worry about

            0|
            ParentPermalink
    • atreides 3 years ago+ 1 comment

      I think you forgot that str instance string. See the requirements. That's something they use to test this. IDK how.

      1|
      ParentPermalink
      • ivanbessonov 3 years ago+ 0 comments

        I avoided str instance for purpose, because I didn't want to spoil whole solution

        1|
        ParentPermalink
    • ahmad_elyaszada 3 years ago+ 0 comments

      Aggreed

      0|
      ParentPermalink
  • Devishwash 3 days ago+ 0 comments

    Here is My'Solution

    class Singleton{
        public String str;
       static Singleton s= new Singleton();
        private Singleton(){    
        }
        public static Singleton getSingleInstance(){
            return s;
        }
    }
    
    0|
    Permalink
  • iamvisshu 3 months ago+ 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;
        }
    }
    
    0|
    Permalink
  • 18dcs024 4 months ago+ 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;
        }
    }
    
    0|
    Permalink
  • siddharth_nawani 4 months ago+ 0 comments
    public String str;
    public static Singleton singleton = null;
    
    private Singleton() {
    
    }
    
    static Singleton getSingleInstance() {
    
        if (singleton == null)
            singleton = new Singleton();
        return singleton;
    
    }
    
    0|
    Permalink
  • Harioom 4 months ago+ 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); } }

    0|
    Permalink
  • benbasty 4 months ago+ 0 comments
    class Singleton{
        private Singleton() {}
        public String str;
        private static final Singleton instance = new Singleton();
        public static Singleton getSingleInstance() {        
            return instance;
        }
    
    }
    
    0|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature