Is initialized non final static variables are thread safe? - java

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.

Related

Making a singleton have all static fields

I always wondered, since a singleton allows use to have just have one reference to an object, which we get by using the static method getInstance, why can’t we decide to make all fields in a singleton static?
Static members are part of class and thus remain in memory till
application terminates and can’t be ever garbage collected. Using
excess of static members sometime predicts that you fail to design
your product and trying to cop of with static / procedural
programming. It denotes that object oriented design is compromised.
This can result in memory over flow. Also there are certain
disadvantages if you make any method static in Java for example you
can not override any static method in Java so it makes testing harder
you can not replace that method with mock. Since static method
maintains global state they can create subtle bug in concurrent
environment which is hard to detect and fix.
So by making every method static we eliminate the purpose of making singleton class which is to Saves memory

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

Does static provide additional guaranties in JMM context?

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.

performance of static vs non static method for an utility class

I have a utility class which has non static methods with no instance variables. So I am thinking of converting all the methods to static methods. I doubt there will be any memory or performance impacts. But I just wanted to confirm.
Will changing such a method to be a static have any performance impact on the program?
One final thing to add to what people have said here.
Using a static method has a slightly less overhead due to the fact that you have guaranteed compile time binding. Static method calls will create the bytecode instruction invokestatic. ]
In a typical scenario, instance methods are bound at runtime, and will create the bytecode instruction invokevirtual which has higher overhead than invokestatic.
However, this only becomes relevant in the case of likely millions of iterations, and i would caution against this driving your class design. Do what makes sense from a design perspective. Based on your description, static methods are probably the way to go. In fact, this is relatively standard practice to create a utility class:
public class MyUtilities {
private MyUtilities() { } // don't let anyone construct it.
public static String foo(String s) { ... }
}
EDIT: Addressing the performance aspect: it's cheaper not to have to create an instance of something pointlessly, but the difference is very likely to be completely irrelevant. Focusing on a clear design is much more likely to be important over time.
Utility methods are frequently static, and if all the methods within a class are static it may well be worth making the class final and including a private constructor to prevent instantation. Fundamentally, with utility classes which don't represent any real "thing" it doesn't make logical sense to construct an instance - so prevent it.
On the other hand, this does reduce flexibility: if any of these utility methods contain functionality which you may want to vary polymorphically (e.g. for testing purposes) then consider leaving them as instance methods - and try to extract some meaningful class name to represent the "thing" involved. (For example, a FooConverter makes sense to instantiate - a FooUtil doesn't.)
There are two requirements that must be met for a method to be eligible for conversion into static:
no instance variables accessed (this is met in your case);
will never need to be subject to overriding (for this you may have to think it through).
However, when these requirements are met, it is actually recommended to make the method static because it narrows down the context the method is run within.
Finally, note that there are no performance issues to talk about here and any theoretical difference is in fact in favor of static methods since they don't involve dynamic method resolution. However, instance method invocation is blazing fast in any relevant JVM implementation.
As far as memory, the story is the same: a theoretical difference is in favor of the static method, but there is no practical difference if compared against a singleton utility class.
If the utility class is not subclassed, converting methods that do not access the instance variables to static is a good idea. You should go through the code and convert invocations to static syntax, i.e.
int res = utilityInstance.someMethod(arg1, arg2);
should be converted to
int res = UtilityClass.someMethod(arg1, arg2);
for clarity.
There will be no noticeable performance impact: although theoretically static invocations are slightly less expensive, the difference is too small to consider important in most scenarios.
It is common for utility classes without state(like java.lang.Math for example) to have public static methods. This way you don't need to create an instance of the class to use it.
Static method good idea when you are going to use the particular functionality very often.
The difference is that you need an instance in order to use them, so the user has to make an instance which will be a

How does static work in a multi threaded environment?

If I have static class, how does jvm guarantee it is initialized once? What happens when two threads simultaneously try to access this first time? Is this feature language invariant?
EDIT : It is about a class which has static variables.
The JVM guarantees that ANY class is initialised exactly once.
What exact low-level mechanism is uses to do this is really JVM-specific, but the thing you need to know as a programmer is that it IS thread-safe per se to attempt to access/initialise the same class from different threads. (Of course, that just goes for class-loading: in terms of accessing any immutable data, be it static or of a particular instance, you need to take appropriate measures.)
You can have a static nested class and the behaves like any other class.
I assume you are referring to static code/blocks and class initialisation. The JVM guarantees that a class will be loaded by only one thread. Since its builtin to the JVM I don't imagine any languages wouldn't use it.
First off, the static keyword is not that commonly used in class declarations, although it can be used there, but means something different than it does for variables or methods.
Did you really want to know about static classes? Or was it a question about static variables/methods?
Static anything is initialized when the class is loaded, not when the first thread attempts to access it. However, static for a class is not the same as static for a data member or function/method. See this article for more information about that. If you are asking about data members, if they are static, then they are considered to be "class variables" or "class methods" not "object variables" (see this article from Oracle for that discussion). It accomplishes that by making them part of the class object itself rather than the instances. There is only ever one class object for any given class.
With regards to your question about other languages: no, static can mean many different things depending on the language.

Categories