In my previous post about singleton pattern in C#, it is very nice flexible singleton code which make us be able to create a singleton instance of a non singleton class. But we can still be able to create a non singleton instance of the target class.
In this post I want to implement it in Java. As far as I know even though both C# and Java have generic feature, generic in C# quite different from the one in Java. While converting of what I did about generic singleton in C# to Java, I feel that the way I do in Java is not as elegant as in C#. The following code is the generic singleton code I write in Java.
Again, if we see from the sample code above it seems that generic singleton in C# is more elegant than in Java.
The main thing that I should do is I have to use HashMap collection to hold any instance of what that want to be as singleton and reuse for the future need in the life cycle of my application.
Anyway, if you have better and much more elegant solution how to implement generic singleton pattern in Java I am very appreciate for any suggestion. Finally I would like to thank you very much for visiting and reading my blog, and have a nice day.
Update March 11, 2016
If you want to the java singleton above, please ensure you have remove / clean up method to clean up HashMap contents if the singleton objects are not needed anymore. At least at the end of application lifecycle, the HashMap and its contents should be removed completely from memory.