Micron Interview Question
Software EngineersTeam: CMS
Country: United States
It's normally preferable to use a Static helper class to create Singletons. That way you can assured that the singleton instance was created. And this approach doesn't require the use of synchronization. Also, the code above doesn't declare the singleton as final.
public class MySingleton{
private static class HELPER{
private static final MySingleton instance = new MySingleton();
}
MySingleton s = HELPER.instance;
}
There are following problems:
* public constructor
* Not Thread safe
* If you synchronise the method the second question would come about whether synchronisation is needed at all, since once the instance is created there is no use of the method access to be synchronised. So you should be aware of double check locking implementation.
Having volatile makes sure non of the threads have a local dirty copy of the instance.
First, a small nitpick: it's Singleton, not Singelton, but this is probably not the sort of advice you're looking for.
- 010010.bin August 23, 2015There is nothing in your class that forces usage of the getInstance() method to get a MySingleton instance. Usually, it is considered good practice to make the constructor private, to prevent other code from inadvertently calling the constructor and obtain another instance. If this was part of an interview question, then I'd say this is what the interviewer was looking for - after all, if you really know what the Singleton pattern is all about, you should know that the code should *forbid* creation of other instances. You do it by making the constructor private.