Static variables and multithreading in java Static variables and multithreading in java multithreading multithreading

Static variables and multithreading in java


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.


Static fields gave one value per class-loader.

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


There is one copy of static variable per class-loader that loaded this class. This more-or-less means per-process, however you need to be aware of the difference.

E.g. when two web-apps have the same class bundled, the class will be loaded twice, thus having two copies of the same static field.

If you need a variable having independent value on a thread basis, have a look at ThreadLocal.