Java Singleton Pattern

  • + 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();
        }
    }
    
    • + 1 comment

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

      • + 0 comments

        I have same error. why?

    • + 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)

      • + 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!

        • + 1 comment

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

          • + 0 comments

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

    • + 1 comment

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

      • + 0 comments

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

    • + 0 comments

      Aggreed