I was wondering about singleton in enum and it's performance.
When we have multithreaded environment we have to synchronize moment, when an instance is created.
Simply, we can use synchronized mod, for function called getInstance() which create instance
Somethink like that:
public synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
It's lazy implementation it's good for me. But synchronized method is slow.
We can use double-locking to make it faster.
How about enum?
When we implement singleton as enum, instance of singleton will be created as first use. Next use, return current instance.
How it works?
When we want to get existing instance, there is implicit synchronized method which are slow? Or there is Double-lock implemented?
Enum is thread-safe and is also the recommended way to implement a Singleton.
That said, enum is not lazily loaded. If you want a lazy-loaded singleton, you can use the Holder pattern (which is thread-safe as well):
class LazySingleton {
private LazySingleton() {}
private static class SingletonHelper{
private static final LazySingleton INSTANCE = new LazySingleton();
}
public static LazySingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
There is no lazy initialization with an enum. It will simply create the instance when the class is loaded.
When we implement singleton as enum, instance of singleton will be created as first use.
That is only true if by "first use" you actually mean "when the class is loaded".
In other words, using your example, an enum would be equivalent to:
private static final Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
The initialization of enum constants happens in the class initializer, similar to had you written
static final Singleton instance = new Singleton();
or
static final Singleton instance;
static {
instance = new Singleton();
}
The safety comes from the fact that the JVM perform class initialization under a JVM specific lock:
Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. … The implementation of the Java Virtual Machine is responsible for taking care of synchronization and recursive initialization by using the following procedure.
…
For each class or interface C, there is a unique initialization lock LC. The mapping from C to LC is left to the discretion of the Java Virtual Machine implementation.
…
I left out a lot of technical details from the specification, as to a Java programmer, the most important point is that there is a safety mechanism implemented by every conforming JVM. The end of the section has the comment:
An implementation may optimize this procedure by eliding the lock acquisition in step 1 (and release in step 4/5) when it can determine that the initialization of the class has already completed, provided that, in terms of the memory model, all happens-before orderings that would exist if the lock were acquired, still exist when the optimization is performed.
This is, of course, an important point of this implementation of the singleton pattern, that later access to the static final field does not need to acquire a lock. Since all classes go from the uninitialized to the initialized state exactly once and it affects every operation (including all other possibilities to implement the singleton pattern), you can expect every JVM to do this fundamental optimization. Even if a particular JVM does not do this, the static final field would be the fastest lazy singleton implementation on that virtual machine…
Related
So far I have seen two examples of Singletons.
Normal Singletons,
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {
// hidden constructor
}
public static Singleton getInstance() {
return instance;
}
}
and Lazy Singletons,
public class Singleton {
private Singleton() {
// hidden constructor
}
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
Coding is from this thread and this user. I have just recently gotten into trying to learn Singletons as my previous methods have been
1.) Using static in order to create something like ...
static MyClass instance;
2.) I would attempt to pass an instance in a seemingly odd way,
MyClass instance;
#Override
public void onEnable() { instance = this; }
// Transition to different class - - -
public OtherClass(MyClass myClass) {
this.instance = myClass;
}
Lastly, what is my end goal? I am mainly using it in order to pass variables from my main class to other classes. I'm currently attempting to learn how to properly use Files and FileConfiguration, so I want to easily share them throughout my classes.
If I seem like a beginner, instead of going out of your way to tell me to learn Java, please provide a resource to help me with my problem first and foremost.
As to when, rather than how: I would use lazy instantiation of a singleton or of any other object when there is a fair chance of the object not being needed, and immediate instantiation when the likelihood of it being needed is high. In general, if instantiation were to fail, and the object is needed, it is better that it fail as early as possible.
This link explains it fairly well and even uses a similar example.
In software engineering, the initialization-on-demand holder (design pattern) idiom is a lazy-loaded singleton. In all versions of Java, the idiom enables a safe, highly concurrent lazy initialization with good performance.
Regarding why you should use this: if the creation of this instance is expensive, then this design pattern essentially delegates the expensive computation for when it is needed, rather than when the outer class, Singleton in your case, is first accessed.
Another reason is given by this other link. It states:
A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method might be called from multiple threads simultaneously, measures may need to be taken to prevent race conditions that could result in the creation of multiple instances of the class.
Usually I use the first implementation. Couple of days ago I found another.
Can anyone explain me the difference between these 2 implementations ?
The 2nd implementation is thread safe?
What is the advantage of using inner class in the 2nd example?
//--1st Impl
public class Singleton{
private static Singleton _INSTANCE;
private Singleton() {}
public static Singleton getInstance(){
if(_INSTANCE == null){
synchronized(Singleton.class){
if(_INSTANCE == null){
_INSTANCE = new Singleton();
}
}
}
return _INSTANCE;
}
}
//--2nd Impl
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton _INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder._INSTANCE;
}
}
The first implementation uses what is called a "double checked lock". This is a Very Bad Thing. It looks thread-safe, but in fact it is not.
The second implementation is, indeed, thread-safe.
The explanation for why the first implementation is broken is fairly involved, so I'd recommend you get a copy of Brian Goetz's Java Concurrency in Practice for a detailed explanation. The short version is that the compiler is allowed to assign the _INSTANCE variable before the constructor has completed, which can cause a second thread to see a partially-constructed object.
The first implementation is only and only thread-safe if the _INSTANCE is made volatile. The second one is thread safe because the _INSTANCE is only initialized once the SingletonHolder is loaded by the class loader.
So when the inner class is accessed for the time (much later than the whole program was loaded), the class loader loads the inner-class and initializes the variable. So for any later access, the object is readily available
Hence the method getInstance() is thread-safe.
The beauty of the second implementation, is you dont have to worry about synchronization or count as class loader does it for you
#1 is designed to ensure lazy initialization. But, in the given case, #2 ensures lazy initialization too. _INSTANCE is created only when Singleton.class is loaded, and Singleton.class is loaded on first invocation of getSingleton(). There is no other method in the class. No double checked locking needed. And of course in #1 _INSTANCE should be volatile.
Note: I do not agree that double checked locking is bad. When implemented correctly it may be very useful.
The first code snippet is an example of the double-checked locking idiom, which used to be quite popular but is now known to be unsafe and should never be used.
The second snippet uses the combination of the semantics of class loading and of the final keyword, as defined by the Java language specification, to ensure lazy initialization and thread safety, so it is much better.
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
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.
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;
}