What is the proper way to initialize java enum based singleton, if I have to initialize it before I can use the object.
I have started writing the code , but I am not sure if I am doing it right. Could you help me to implement this singleton correct for me?
public enum BitCheck {
INSTANCE;
private static HashMap<String, String> props = null;
public synchronized void initialize(HashMap<String, String> properties) {
if(props == null) {
props = properties;
}
}
public boolean isAenabled(){
return "Y".equalsIgnoreCase(props.get("A_ENABLED"));
}
public boolean isBenabled(){
return "Y".equalsIgnoreCase(props.get("B_ENABLED"));
}
}
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards.
The singleton pattern restricts the instantiation of a class to one object. INSTANCE is a public static final field that represents the enum instance. We can get the instance of the class with the EnumSingleton. INSTANCE but it is better to encapsulate it in a getter in case if we want to change the implementation.
1) Enum Singletons are easy to write This is by far the biggest advantage if you have been writing Singletons prior ot Java 5 than you know that even with double-checked locking you can have more than one instance.
You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes. BUSSINESS_ERROR. Each constant in the enum has only one reference, which is created when it is first called or referenced in the code.
It's perfectly possible to create constructor for enum
:
public enum BitCheck {
INSTANCE;
BitCheck() {
props = new HashMap<String, String>();
}
private final Map<String, String> props;
//..
}
Note that:
props
field can be final (we like final
)props
doesn't have to be static
Pay attention to the last point. Since enum
-singletons are created eagerly when the enum BitCheck
class is loaded, you have no way to pass any arguments to the constructor. Of course you can through INSTANCE
declaration:
public enum BitCheck {
INSTANCE(new HashMap<String, String>());
BitCheck(final Map<String, String> props) {
this.props = props;
}
but this doesn't make any difference, right? What do you want to achieve? Maybe you actually need lazy-initialized singleton?
You have to just initialize it in declaration.
public enum BitCheck {
INSTANCE;
private final Map<String, String> props = new ConcurrentHashMap<String, String>();
public void putAll(HashMap<String, String> map) {
props.putAll(map);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With