Writing a singleton is not that hard but writing it the right way may not be all that trivial. I wrote hundreds
singletons in my developer life and yesterday I found, thanks to a
Wikipedia post,
what I think is the perfect solution. The solution is not mine but I report it here for future reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
In this implementation the singleton instance is thread safe and unique as this is warranted by using final and static keywords. Moreover the singleton instantiation is as lazy as possible: the singleton instance will be created if and only if you call the getInstance() method and not whenever you simply reference the Singleton class (like accessing a constant).