I have a singleton that keeps its current state inside of an enum. I want to be sure that this implementation is thread-safe, does not have serialization issues and is performant. It is being used for central configuration and to dynamically change the configuration at run-time. May anyone please point out any issues that you can find. I realize the synchronized blocks may slow the access to an internal enum value.
The set operation is not called very often maybe once a day, but the get operation is called 200-600 times an hour.
I have tried running this with different threads accessing the value and setting value in the enum.
import java.io.Serializable;
public class ProviderSingleton implements Serializable {
private static final long serialVersionUID = -6827317560255793250L;
private static volatile EmailProvider emailProvider;
private static ProviderSingleton instance = new ProviderSingleton();
private ProviderSingleton() {
System.out.println("Singleton(): Initializing Instance");
emailProvider = EmailProvider.SMTP; // the default
}
public static ProviderSingleton getInstance() {
return instance;
}
public String getEmailProvider() {
synchronized (ProviderSingleton.class) {
return emailProvider.name().toString();
}
}
public void setEmailProvider(String emailProviderValue) {
synchronized (ProviderSingleton.class) {
emailProvider = EmailProvider.valueOf(emailProviderValue);
}
}
// This method is called immediately after an object of this class is
// deserialized.This method returns the singleton instance.
protected ProviderSingleton readResolve() {
return getInstance();
}
enum EmailProvider {
SMTP, POP3;
}
}
I am hopping issues can be pointed out or improvements suggested with code examples.