I found that declaring a variable as static makes no sense
in Multi-Threading. I assume that, this is because of every thread has its own stack
. Is this the only reason?
I know that static variables should be used within synchronized block
. but why?
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.
Add volatile
to your static declaration.
volatile
will guarantee any other thread will see the most recent value of the variable. So, with volatile it will make sense.
However, volatile
will not guarantee atomicity. If you write to your variable from more than one thread you might want to use atomics or synchronize
block.
I think volatile
will be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With