You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
ensure that only one instance of the singleton class ever exists;
and provide global access to that instance.
Typically, this is done by:
declaring all constructors of the class to be private;
and providing a static method that returns a reference to the instance.
The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called.
The intuitive implementation has thread safety problems (wrong examples, see ref.) This implementation using JVM mechanism itself guarantee the thread safety issue:
SingletonHolder is private, there is no access except getInstance(), therefore it's lazy initialization;
Meanwhile no synchronizing when reading the instance, prevent from a poor performance;
No depandance to any specific JDK version.
2. enum typed class
publicenumSingleton{
INSTANCE;
}
A real elegant implementation. Access from EasySingleton.INSTANCE, easier than calling getInstance() as above.
Creating a enum instance is thread-safe by default, so no thread safety issue. But thread safety of any other method is responsible to programmer himself.
Features (wiki):
(Almost) Best Practices:
1. private static internal holder:
The intuitive implementation has thread safety problems (wrong examples, see ref.) This implementation using JVM mechanism itself guarantee the thread safety issue:
SingletonHolder
is private, there is no access exceptgetInstance()
, therefore it's lazy initialization;2. enum typed class
A real elegant implementation. Access from
EasySingleton.INSTANCE
, easier than callinggetInstance()
as above.Creating a enum instance is thread-safe by default, so no thread safety issue. But thread safety of any other method is responsible to programmer himself.
Ref.: http://coolshell.cn/articles/265.html
The text was updated successfully, but these errors were encountered: