Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables and multithreading in java

Tags:

Is a static member of a class present as only a single instance per process or thread? Meaning does each thread has its own copy of the static member variable of the class?

My guess is per process, am I correct?

like image 575
shawn Avatar asked Dec 08 '11 14:12

shawn


People also ask

Is static variables are thread safe in Java?

Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.

Can we use static method in multithreading Java?

So while thread confinement of an object is a valid thread safety policy for instances of a class, this same reasoning is invalid for static methods because they have no instance.

Are static final variables thread safe?

Final variables are immutable references, so a variable declared final is safe to access from multiple threads. You can only read the variable, not write it. Be careful, because this safety applies only to the variable itself, and we still have to argue that the object the variable points to is immutable.

Does static methods are thread safe?

A data type or static method is threadsafe if it behaves correctly when used from multiple threads, regardless of how those threads are executed, and without demanding additional coordination from the calling code.


2 Answers

Is a static member of a class present as only a single instance per process or thread?

static fields have one value per class-loader but I think the meat of your question is in the following:

each thread has its own copy of the static member variable of the class

This is correct although the devil is in the details. Each thread may have it's own copy of the field in it's own local memory space/cache unless the field has been marked with volatile which forces the field to be surrounded with a memory barrier which causes a memory synchronization on each access/update.

Without volatile, any updates and reads to a static field will be made to local thread storage and only updated whenever a thread crosses a memory barrier. Without the memory barriers, there are no guarantees around the order of data operations and when the updates will be shared with other threads.

Here's a decent page about the Java memory model and a good overview of some of the challenges.

like image 197
Gray Avatar answered Oct 06 '22 07:10

Gray


Static fields gave one value per class-loader.

If you want a per-thread value, make a static ThreadLocal<T>.

like image 21
SLaks Avatar answered Oct 06 '22 07:10

SLaks