I currently have a program implementing a Singleton design pattern:
public class Singleton {
private static Singleton s;
private Singleton(){
}
public static Singleton getInstance(){
if(s == null){
s = new Singleton();
}
return s;
}
}
I was asked in an interview that given a program like this, what are some good options to make the getInstance method thread safe. I know that one method is just to tag synchronized before the method, but the interviewer said there were other more efficient ways to deal with making methods thread safe.
Can anyone offer any ideas?
At least three I can think of, although two of those boil down to the same principle.
Basically you can either let the classloader worry about thread-safety or use double-checked locking from Java5 onwards.
The first versions means having an inner class/enum that contains the actual code, the second that you make the Singleton instance volatile and use the usual if-synchronize-if solution.
Oh my word, not this again.
The very best way to write this is the simplest:
public class Singleton {
private static Singleton s = new Singleton();
// ...
}
Making the getter synchronized is the second best. There are a few more complex ways to do it, but none of them are worth the effort -- synchronized is very cheap, and don't let anyone tell you otherwise.
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