static variables in multithreading

后端 未结 4 744
耶瑟儿~
耶瑟儿~ 2021-01-02 07:04

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

相关标签:
4条回答
  • 2021-01-02 07:08

    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.

    0 讨论(0)
  • 2021-01-02 07:11

    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.

    0 讨论(0)
  • 2021-01-02 07:12

    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.

    0 讨论(0)
  • 2021-01-02 07:17

    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.

    0 讨论(0)
提交回复
热议问题