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
Related
I am reading about java singleton and I've met strange things.
I will refer to following artice as example(you can easy find more)
Author provides the following singleton:
public class ASingleton {
private static ASingleton instance = new ASingleton();
private ASingleton() {
}
public static ASingleton getInstance() {
return instance;
}
}
and comments:
Pros:
-Thread safety without synchronization
- Easy to implement
Cons:
- Early creation of resource that might not be used in the application.
-The client application can’t pass any argument, so we can’t reuse it.
For example, having a generic singleton class for database connection
where client application supplies database server properties.
I want to get clarification about Thread safety without synchronization point.
I've read concurrency in practice book and don't remember anything related with this.
I missed something or this clarification is not relevant?
Additionally I want to tell you that you can encounter the same singleton but field marked as static final instead of just static
P.S.
I understand that I can read JMM and this one contains the answer but I am usual guy and I can't undertand this source.
According to securecoding.cert.org this is a valid pattern:
Variables that are declared static and initialized at declaration or from a static initializer are guaranteed to be fully constructed before being made visible to other threads. However, this solution forgoes the benefits of lazy initialization.
The point is: loading classes is a well defined operation. And executing static initializing code falls into the same category.
It is important to understand: JMM knowledge is only "required" when you go for the static field + lazy init variant:
Initialization of the static helper field is deferred until the getInstance() method is called. The necessary happens-before relationships are created by the combination of the class loader's actions loading and initializing the Holder instance and the guarantees provided by the Java memory model (JMM). This idiom is a better choice than the double-checked locking idiom for lazily initializing static fields [Bloch 2008]. However, this idiom cannot be used to lazily initialize instance fields [Bloch 2001].
Finally: the final keyword should not affect this at all. Using final is much more about expressing your intent to declare a well, final thing - instead of one that gets potentially updated later on.
That idiom is sound with respect to the JMM.
There is a happens before relationship between the static initialization of a class and the use of any static variables. This is a consequence of the locking that occurs during the initailization procedure described in JLS 12.4.2.
According to my reading, instance does not need to be declared as final here to get the required happens-before. It is advisable for other reasons though.
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?
Assume, I have a private non final static variable, and initialized in the static block, and it is not modified after initialization and has no methods to modify the variable. Is it threadsafe?
class Test
{
private static int value = 10;
public static int getValue()
{
return value;
}
}
I just wanted to know what guarantee JVM provides with non final static variables with no methods to modify the variable in terms of thread safety, where multiple threads try to read the data.
The procedure for initializing a class (JLS 11.4.2) states that that initialization is performed while holding a lock. I think that this implies that any thread that refers to the statics after initialization has completed will see the fully initialized state.
You might get into trouble if you had a situation where the static initialization of one class created and started a thread that could observe the static variables of another class before they latter's static initialization completed. In that case, it may not be possible to guarantee that the thread will see the initialized state.
The other think to note is that we are only talking about the values in the static variables here. If those variables refer to mutable objects or arrays, and those objects / arrays are mutated, then your code is not automatically thread-safe.
This illustrates a larger point. You can't actually talk about the thread-safety of variables in isolation. The accepted definition of thread-safety is that the introduction of threading does not result in incorrect behaviour of something. Variables don't have behaviour. Behaviour is an application level thing, though it is sometimes meaningful to consider the behaviour of a part of an application; e.g. some classes or methods in a particular application context.
Reading between the lines ... you seem to be trying to avoid the "overheads" of synchronization in your usage of statics. That is all well and good ... but the thread-safety, static initialization and the memory model are all some of the most difficult / hard to understand parts of the Java language. Many really smart people have (in the past) tried and failed when implementing "clever" or "efficient" ways of reducing synchronization overheads.
My advice: don't try to be too smart. Keep it simple. The synchronization overheads are not large enough (IMO) to risk introducing "heisenbugs" into your code-base.
And finally, it is generally accepted that static variables, and especially mutable static variables are bad OO design. I would advise you to consider revising your design to eliminate them.
Is the following code threadsafe ?
public static Entity getInstance(){
//the constructor below is a default one.
return new Entity();
}
Assuming the constructor itself is thread-safe, that's fine.
It would be very unusual for a constructor not to be thread-safe, but possible... even if it's calling the default auto-generated constructor for Entity, the base constructor may not be thread-safe. I'm not saying it's likely, just possible :)
Basically there's no magic thread-safety applied to static methods or instance methods or constructors. They can all be called on multiple threads concurrently unless synchronization is applied. If they don't fetch or change any shared data, they will generally be safe - if they do access shared data, you need to be more careful. (If the shared data is immutable or only read, that's generally okay - but if one of the threads will be mutating it, you need to be really careful.)
Only static initializers (initialization expressions for static variables and static { ... } blocks directly within a class) have special treatment - the VM makes sure they're executed once and only once, blocking other threads which are waiting for the type to be initialized.
It depends on the details of the Entity constructor. If the Entity constructor modifies shared data, then it is not.
It's probably thread safe, but what's the point? If you're just using a factory method to redirect to the default constructor then why not use the constructor in the first place? So the question is: what are you trying to achieve? The name getInstance() suggests a singleton (at least that's common practice), but you clearly don't have a singleton there. If you do want a singleton, use a static inner holder class like this:
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
private static final class InstanceHolder {
public static final Singleton INSTANCE = new Singleton();
}
}
but if you don't, why bother with such a factory method, as you're not adding any value (method name semantics, object pooling, synchronization etc) through it
Thread safety is about access to shared data between different threads. The code in your example doesn't access shared data by itself, but whether it's thread-safe depends on whether the constructor accesses data that could be shared between different threads.
There are a lot of subtle and hard issues to deal with with regard to concurrent programming. If you want to learn about thread safety and concurrent programming in Java, then I highly recommend the book Java Concurrency in Practice by Brian Goetz.
Multiple threads could call this method and each one will get an unique instance of 'Entity'. So this method 'per se' is thread safe. But if there is code in the constructor or in one of the super constructors that is not thread safe you might have a safety problem anyhow.
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;
}