Does static provide additional guaranties in JMM context? - java

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.

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

Is initialized non final static variables are thread safe?

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.

Singleton's other members

My question is broad, so I've split in two parts, and tried to be as specific as I can with what I know so far.
First part
A singleton holds a private static instance of itself. Some questions about singletons:
1. Should it's members also be static, or does that depend on the requirements?
2. If the answer to 1. is unequivocally yes, then what would be the point of having a private instance variable to begin with, if all members belong to the class?
3. Is the private instance needed because the JVM needs a referable object (THE singleton) to hold on to for the length of its (JVM's) life?
Second part
There is a requirement to make multiple concurrent remote calls within a tomcat hosted web application (the app utilizes GWT for some components, so I can utilize a servlet for this aforementioned requirement if a good solution requires this). Currently, I create an executor service with a cached thread pool into which I pass my callables (each callable containing an endpoint configuration), for each individual process flow that requires such calls. To me it would make sense if the thread pool was shared by multiple flows, instead of spawning pools of their own. Would a singleton holding a static thread pool be a good solution for this?
One note is that it is important to distinguish between the concept of a singleton (a class/object that has only a single instance) and the design pattern which achieves this via a class holding a single static instance of itself accessible in the global static name space. The concept of a singleton is frequently used in designs, the implementation of it via the singleton design pattern, however, is often frowned upon.
In the below, singleton is used to refer to the specific design pattern.
Part 1
A Singleton's members do not need to be static, and usually are not.
See 1.
A singleton (design pattern) requires an instance to itself in order to return that instance to users of the singleton, as well as keeping a reference to itself active to avoid garbage collection (as you suggest). Without this single instance, the object is essentially not an implementation of the singleton design pattern. You can create a class for which you only create a single instance and pass this class around where it is required (avoiding the global static namespace), and this would essentially be a recommended way to avoid using the singleton pattern.
Part 2:
Sharing your thread pools is probably wise (but depends on your requirements), and this can be done in a number of ways. One way would be to create a single pool and to pass this pool (inject it) into the classes that require it. Usual recommendation for this is to use something like Spring to handle this for you.
Using a singleton is also an option, but even if your thread pool here is encapsulated in a singleton, it is still generally preferable to inject this singleton (preferably referenced via an interface) into dependent objects (either via a setter or in their constructor) instead of having your objects refer to the singleton statically. There are various reasons for this, with testing, flexibility, and control over order of instantiation being some examples.
A Singleton's members need not be be static.
Invalidated by answer to point 1.
The instance of itself that the singleton need not be private either. You need an instance stored to a static member (public or private) if you have any other non-static member on the singleton. If there is any non-static member(it depends on your requirement) , then you need an instance to access that member(yes, JVM needs a referable object if the member is non-static)
Singleton member doesn't need to be static
Look at point 1
Singleton instance must be static (of course) and must be accessed by a static method; in addiction must have a private constructor to prevent new instance to be created
public class SingletonNumber10 {
public static SingletonNumber10 getInstance() {
if(null == instance) {
instance = new SingletonNumber10(10);
}
return instance;
}
private int number;
private static SingletonNumber10 instance;
private SingletonNumber10(int number) {
this.number = number;
}
public int getNumber() {
return this.number;
}
public static void main(String[] args) {
System.out.println(SingletonNumber10.getInstance());
System.out.println(SingletonNumber10.getInstance());
}
}
A singleton holds a private static instance of itself.
Not always, in fact, that's not even the best way to do it in Java.
public enum Director {
INSTANCE;
public int getFive() {
return 5;
}
}
Is a perfectly valid singleton, and is far more likely to remain the only copy in existence than a class that holds a private static instance of itself.
1. Should it's members also be static
No, the members should not be static, because then there is no need for a class, and therefore no need for that class to be a singleton. All static routines are subject to code maintenance issues, similar to C / C++ functions. Even though with singletons you won't have multiple instances to deal with, having the method off of an instance provides you with certain abilities to morph the code in the future.
2. If the answer to 1. is unequivocally yes.
It's not, so no need to answer #2.
3. Is the private instance needed because the JVM needs a
referable object (THE singleton) to hold on to for the
length of its (JVM's) life?
No, the private instance is needed because you have to have some ability to determine if the constructor was called previous to the access. This is typically done by checking to see if the instance variable is null. With race conditions and class loader considerations, it is incredibly difficult to make such code correct. Using the enum technique, you can ensure that there is only on instance, as the JVM internals are not subject to the same kinds of race conditions, and even if they were, only one instance is guaranteed to be presented to the program environment.
There is a requirement to make multiple concurrent remote calls within
a tomcat hosted web application (the app utilizes GWT for some components,
so I can utilize a servlet for this aforementioned requirement if a good
solution requires this). Currently, I create an executor service with a cached
thread pool into which I pass my callables (each callable containing an endpoint
configuration), for each individual process flow that requires such calls. To
me it would make sense if the thread pool was shared by multiple flows, instead
of spawning pools of their own. Would a singleton holding a static thread pool be
a good solution for this?
It depends. What are the threads in the pool going to be doing? If it's a thread to handle the task, eventually they will all get tied up with the long running tasks, possibly starving other critical processing. If you have a very large number of tasks to perform, perhaps restructuring the processing similar to the call-back patterns used in NIO might actually give you better performance (where one thread handles dispatching of call-backs for many tasks, without a pool).
Until you present a second way of handling the problem, or make more details of the operating environment available, the only solution presented is typically a good solution.
PS. Please don't expand on the details of the environment. The question submission process is easy, so if you want to expand on the second part, resubmit it as an independent question.

static class vs singleton class

I know this topic has been discussed and killed over and over again, but I still had one doubt which I was hoping someone could help me with or guide me to a pre-existing post on SO.
In traditional C, static variables are stored in data segments and local variables are stored in the stack. Which I would assume will make static variables more expensive to store and maintain when compared to local variables. Right?
When trying to understand in terms of Java or C#, would this be dis-advantage for static classes when compared to singleton class? Since the entire class is loaded into memory before class initialization, I don't see how it can be an advantage unless we have small inline-able functions.
I love Singleton classes, and would hate to see it become an anti-pattern, I am still looking for all the advantages that come with it...and then loose to the argument of thread-safety among others.
-Ivar
Different from C, the static keyword in Java class definition merely means, This is just a normal class like any other class, but it just happens to be declared inside another class to organize the code. In other words, there is no behavioral difference whatsoever between the following 2 way of declaration*:
a)
class SomeOtherClass {
static class Me {
// If you "upgrade" me to a top-level class....
}
}
b)
class Me {
// I won't behave any different....
}
Class definitions are loaded to memory when the class is used for the first time, and this is true for both "static" and "non-static" classes. There are no difference in how memory will be used, either. In older JVMs, objects were always stored in heap. Modern JVMs do allocate objects on stack when that is possible and beneficial, but this optimization is transparent to the coder (it is not possible to influence this behavior via code), and use of the static keyword does not have any effect on this behavior.
Now, back to your original question, as we have seen we really can't compare static classes and Singleton in Java as they are completely different concept in Java (I'm also not sure how static classes would compare with Singleton, but I will focus on Java in this answer). The static keyword in Java is overloaded and has many meanings, so it can be confusing.
Is Singleton automatically an "anti-pattern"? I don't think so. Abuse of Singleton is, but the Singleton pattern itself can have many good uses. It just happens to be abused a lot. If you have legitimate reason to use the Singleton pattern, there is nothing wrong in using it.
*Note: Why write static at all, you might ask. It turns out "non-static" nested classes have their own somewhat complicated memory management implication, and its use is generally discouraged unless you have a good reason (pls refer to other questions for more info).
class SomeOtherClass {
Stuff stuff;
class Me {
void method(){
// I can access the instance variables of the outer instance
// like this:
System.out.println(SomeOtherClass.this.stuff);
// Just avoid using a non-static nested class unless you
// understand what its use is!
}
}
}
Singleton class is essentially a regular top-level class with a private constructor, to guarantee its singleness. Singleton class itself provides a way to grab its instance. Singleton classes are not very easy to test, therefore we tend to stick with the idea of Just Create Once.
static class is essentially a nested class. A nested class is essentially a outer level class which is nested in another class just for packaging convenience. A top-level class can not be declared as static, in Java at least -- you should try it yourself.
would this be dis-advantage for static
classes when compared to singleton
class?
Your this question became somewhat invalid now, according to the above explanation. Furthermore, a static class (of course nested) can also be a singleton.
Further reading:
Inner class in interface vs in class
The differences between one and the other is the memory management, if your app will have to instantiate a lot of things, that will burn the memory like a charm becoming a memory problem, performance and other things...
this could help...
http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf
I'm afraid it is an anti-pattern:
http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/

static method and thread safety

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.

Categories