Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variables in multithreading

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?

like image 924
R9J Avatar asked Jul 06 '13 06:07

R9J


4 Answers

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.

like image 106
Juned Ahsan Avatar answered Oct 10 '22 10:10

Juned Ahsan


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.

like image 42
Divers Avatar answered Oct 10 '22 09:10

Divers


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.

like image 21
Devolus Avatar answered Oct 10 '22 08:10

Devolus


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.

like image 2
Alexander Kulyakhtin Avatar answered Oct 10 '22 10:10

Alexander Kulyakhtin