When to use proper version of singleton thread-safe implementation? - java

I have a stateless helper-like class which I want to make as a singleton. This class will be shared across different threads.
Am I correct that in this case (instance does not require huge memory allocation size and thus can be loaded several times without resources and performance impact) there is no need in implementing such a singleton with proper multi-threading lazy initialization strategy (Double Checked Locking & volatile, On Demand Holder idiom, Enum Singleton, Synchronized Accessor)?
Is it right to implement such a singleton with a simple non-multi-threading lazy initialization version strategy (like in the code below) in order to have less amount of boilerplate code?
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
And only in case when state of the singleton class shared across different threads it is required to add proper multi-threading version of a singleton initialization?

If your class is entirely stateless - make it a util class with only static functions.
If you have state and want a semi-singleton I would say that what you have done is misleading since there is no way for the reader to know if you were aware of the fact that you can get multiple instances or not. If you decide to stick with your posted code - rename it multiton or document the behaviour carefully. But don't do it just to reduce boilerplate though - you are in fact creating more problems for the reader than you are removing.
In my opinion the "Initialization on Demand Holder" idiom is the nicest singleton pattern. But I would recommend against Singletons in general. You would be better off passing a reference to a shared instance to your thread when you start it.

To answer your question... No, it's not correct.
You say it's OK for it to be loaded several times, but in that case then it's not a singleton. The defining characteristic of a singleton is that there can only ever be one instance.
If it's OK for there to be several, then why make it a singleton at all?
If it's just stateless util methods then why not just make the static?

Related

Does volatile usage slow down the performance

I was reading about volatile when I came across this statement that using volatile and synchronize keyword would slow down your overall performance hence the following code to make a singleton class
public enum Singleton {
INSTANCE
}
Is better making a singleton class which includes a volatile instance and a synchronised method to return that static instance.
Though both the classes are thread safe and give the same desired result. Apart from the code readability , are there are any performance benefits of using enums.
Maybe volatile does not do what you think it does. The text of your question looks like you are asking about two different ways of safely publishing a singleton in a multi-threaded environment. But, that is not what volatile is for. volatile solves a more general problem.
You can declare a variable to be volatile if it needs to be shared between different threads, but it does not need to be synchronized with any other variable. The volatile declaration ensures that any time a thread looks at the variable, it always will see the newest value that was assigned to it, even if that value was assigned by some other thread.
Yes. volatile is costly. It would be a mistake to use it when you don't need it (e.g., it would be a mistake to use it on a variable that is not shared, and it would be a mistake to use it on a shared variable that already is protected by other means.)
synchronized keyword by definition slow down the performance as it allows only one thread to process the synchronized code block. The only reason to use synchronized and volatile for creating a singleton class is to provide for lazy initialization of the single instance of the class.
private static volatile ThreadSafeLazySingleton instance;
private ThreadSafeLazySingleton(){}
public static synchronized ThreadSafeLazySingleton getInstance(){
if(instance == null){
instance = new ThreadSafeLazySingleton();
}
return instance;
}
Lazy initialization is helpful when the instantiation is resource heavy and you want to delay the creation of instance to the last moment.
It is possible to break the singleton design of a class by using Reflection and setting the private constructor Singleton.class.getDeclaredConstructors() access to true by using constructor.setAccessible(true).
Using enum to design a singleton class overcomes the above drawback as Java ensures that enums are always instantiated only once. However, the benefits of lazy initialization are lost in this approach. As synchronization is not used, this approach will have better performance than the synchronized approach.
The best way to design a singleton class is by using the method suggested in this answer

How do I find where an instance of a Java singleton is created?

In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example

Initialize-On-Demand idiom vs simple static initializer in Singleton implementation

Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?
Simple declaration of instance as static field:
class Singleton
{
private static Singleton instance=new Singleton();
private Singleton () {..}
public static Singleton getInstance()
{
return instance;
}
}
vs
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
private Singleton () {..}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I ask this because Brian Goetz recommends the 1st approach in this article:
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
while he suggests the latter in this article
http://www.ibm.com/developerworks/library/j-jtp03304/
Does the latter approach provide any benefits that the former doesn't?
Well what i can say These articles are 7-9 years old.
Now we have > Java 1.5 where we have power of enumeration enum. According to 'Josh Block' The best way to write a singleton is to write a Single Element enum
public enum MySingleton{
Singleton;
// rest of the implementation.
// ....
}
But for your question I guess there is no issue in using either of the implementations. I personaly prefer the first option because its straightforward, simple to understand.
But watch out for the loop holes that we can be able to create more objects of these class in the same JVM at the same time by serializing and deserializing the object or by making the clone of the object.
Also make the class final, because we can violate the singleton by extending the class.
In first approach your singleton will get created once you load Singleton class. In the other, it will get created once you call getInstance() method. Singleton class may have many reasons to get loaded before you call getInstance. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.
The simple declaration pattern constructs the singleton when when the class Singleton is loaded. The initialize-on-demand idiom constructs the singleton when Singeton.getInstance() is called -- i.e., when class SingetonHolder is loaded.
So these are the same except for time; the second option allows you delay initialization. When to choose one or the other depends on (among other things) how much work you are doing in Singleton's constructor. If it's a lot, you may see improved application startup time with initialization-on-demand.
That said, my advice is to try not to do too much there so that the simplest pattern works for you.
-dg

How to make an immutable singleton in Java?

An immutable object is initialized by its constuctor only, while a singleton is instantiated by a static method. How to make an immutable singleton in Java?
while a singleton is instantiated by a
static method
While this is the usual way of doing it, this is by no means the only way.
In Java 1.5 a new version of Singleton is the enum singleton pattern:
public enum Elvis{
INSTANCE // this is a singleton, no static methods involved
}
And since enums can have constructors, methods and fields, you can give them all the immutable state you want.
Reference:
Java tutorial: Enum Types
Effective Java, Item 3
Singleton (the enum way)
(WikiPedia)
Also, the term Singleton leaves some room for interpretation. Singleton means that there is exactly one object per defined scope, but the scope can be a number of things:
Java VM Classloader (thanks #PaĆ­lo Ebermann for reminding me): in this case use enums or the initialize-through-static-inner-class pattern. This is of course what is usually meant by a singleton.
Be Careful: enums and all other singletons are broken if loaded through multiple Classloaders.
Enterprise Application (in this case you need a container-managed singleton, e.g. a Spring singleton bean). This can be several objects per VM or one object per several VMs (or one Object per VM, of course)
Thread (use a ThreadLocal)
Request / Session (again, you'll need a container to manage this, Spring, Seam and several others can do that for you)
did I forget anything?
All of the above can be made immutable, each in their own way (although it's usually not easy for container-managed components)
The solution pointed out by Sean is a good way of initializing singletons if their creation is not expensive. If you want to "lazy loading" capability, look into the initialization on demand holder idiom.
// from wikipedia entry
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {
}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
public enum MySingleton {
instance;
//methods
}
//usage
MySingleton.instance.someMethod();
You're being unnecessary complicated. To be immutable an object must be unmodifiable once it is created. That's normally interpreted to mean "modifiable only in the constructor", but if you were to create it another way that would still make it immutable. As long as your object cannot be modified after it is initialized then it is immutable. You can consider setting up the Singleton instance to be part of the initialization.
Most of the benefits of immutability are irrelevant in Singletons.

proper usage of synchronized singleton?

So I am thinking about building a hobby project, one off kind of thing, just to brush up on my programming/design.
It's basically a multi threaded web spider, updating the same data structure object->int.
So it is definitely overkill to use a database for this, and the only thing I could think of is a thread-safe singleton used to contain my data structure. http://web.archive.org/web/20121106190537/http://www.ibm.com/developerworks/java/library/j-dcl/index.html
Is there a different approach I should look in to?
Double-checked locking has been proven to be incorrect and flawed (as least in Java). Do a search or look at Wikipedia's entry for the exact reason.
First and foremost is program correctness. If your code is not thread-safe (in a multi-threaded environment) then it's broken. Correctness comes first before performance optimization.
To be correct you'll have to synchronize the whole getInstance method
public static synchronized Singleton getInstance() {
if (instance==null) ...
}
or statically initialize it
private static final Singleton INSTANCE = new Singleton();
Using lazy initialization for the database in a web crawler is probably not worthwhile. Lazy initialization adds complexity and an ongoing speed hit. One case where it is justified is when there is a good chance the data will never be needed. Also, in an interactive application, it can be used to reduce startup time and give the illusion of speed.
For a non-interactive application like a web-crawler, which will surely need its database to exist right away, lazy initialization is a poor fit.
On the other hand, a web-crawler is easily parallelizable, and will benefit greatly from being multi-threaded. Using it as an exercise to master the java.util.concurrent library would be extremely worthwhile. Specifically, look at ConcurrentHashMap and ConcurrentSkipListMap, which will allow multiple threads to read and update a shared map.
When you get rid of lazy initialization, the simplest Singleton pattern is something like this:
class Singleton {
static final Singleton INSTANCE = new Singleton();
private Singleton() { }
...
}
The keyword final is the key here. Even if you provide a static "getter" for the singleton rather than allowing direct field access, making the singleton final helps to ensure correctness and allows more aggressive optimization by the JIT compiler.
If your life depended on a few microseconds then I would advise you to optimize your resource locking to where it actually mattered.
But in this case the keyword here is hobby project!
Which means that if you synchronized the entire getInstance() method you will be fine in 99.9% of all cases. I would NOT recommend doing it any other way.
Later, if you prove by means of profiling that the getInstance() synchronization is the bottleneck of your project, then you can move on and optimize the concurrency. But I really doubt it will cause you trouble.
Jeach!
Try the Bill Pugh solution of initialization on demand holder idiom.
The solution is the most portable across different Java compilers and virtual machines.
The solution is thread-safe without requiring special language constructs (i.e. volatile and/or synchronized).
http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh
as Joshua Bloch argues in his book "effective java 2nd edition" I also agree that a single element enum type is the best way to implement a singleton.
public enum Singleton {
INSTANCE;
public void doSomething() { ... }
}
If you look at the very bottom of that article, you'll see the suggestion to just use a static field. That would be my inclination: you don't really need lazy instantiation (so you don't need getInstance() to be both an accessor and a factory method). You just want to ensure that you have one and only one of these things. If you really need global access to one such thing, I'd use that code sample towards the very bottom:
class Singleton
{
private Vector v;
private boolean inUse;
private static Singleton instance = new Singleton();
private Singleton()
{
v = new Vector();
inUse = true;
//...
}
public static Singleton getInstance()
{
return instance;
}
}
Note that the Singleton is now constructed during the installation of static fields. This should work and not face the threading risks of potentially mis-synchronizing things.
All that said, perhaps what you really need is one of the thread-safe data structures available in the modern JDKs. For example, I'm a big fan of the ConcurrentHashMap: thread safety plus I don't have to write the code (FTW!).
Why don't you create a data structure you pass to each of the threads as dependency injection. That way you don't need a singleton. You still need to make the thread safe.
The article you referenced only talks about making the creation of the singleton object, presumably a collection in this case, thread-safe. You also need a thread-safe collection so that the collection operations also work as expected. Make sure that the underlying collection in the singleton is synchronized, perhaps using a ConcurrentHashMap.
Check out this article Implementing the Singleton Pattern in C#
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
How about:
public static Singleton getInstance() {
if (instance == null) {
synchronize(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

Categories