static variables in multithreading static variables in multithreading multithreading multithreading

static variables in multithreading


static makes no sense in Multi-Threading.

Im afraid you are making the reverse statement. Static variable is a shared resource, which can be used to exchange some information among different threads. And we need to be careful while accessing such a shared resource. Hence, we need to make sure that the access to static variables in multi-threaded environment is synchronized.

every thread has its own stack

This is a correct statement. Each thread has its own stack but they share the process heap. Stack holds only the local variables and not the variables on the heap. Static variables are stored in the PermGen section of the heap and hence the access to them should be well guarded.


Because first part of question is already answered, I will try to answer on second question.

I know that static variables should be used within synchronized block. but why?

Because if you don't use atomic, operations with variables are not atomic. That's why you should block variables while working with them. But in real world, you can use volatile keyword, that will guarantee you, that threads will have actual values of variable.


If you change a variable in a multithreaded environment, the new value may not neccessarily visibile as it might be cached. This is also true for static variables of course. If you don't use a synchronized block you might consider using volatile instead. This will also guaruantee that the various threads get an updated copy, without the need of synchronizing.Wether volatile is enough four your application depends on your requirements.