java singleton instantiation

前端 未结 4 992
暖寄归人
暖寄归人 2020-12-24 04:01

I\'ve found three ways of instantiating a Singleton, but I have doubts as to whether any of them is the best there is. I\'m using them in a multi-threaded environment and pr

4条回答
  •  爱一瞬间的悲伤
    2020-12-24 04:31

    The most secure and easy way to implement a singleton in java is by using enums (like you mentioned):

    public enum ClassName {
        INSTANCE;
    
        // fields, setters and getters
    }
    

    The enum semantics guarantees that there will be only one INSTANCE

    If not using the enum approach, you must take care of quite a lot aspects, like race conditions and reflection. I've been breaking singletons of some frameworks, and abusing them, because they weren't properly written. The enum guarantees no one will break it.

提交回复
热议问题