JAVA threads (different stacks) synchronization

后端 未结 8 1624
北恋
北恋 2021-01-05 22:19

I have a question regarding synchronization of code that is executed by several threads:

As far as I know each thread has its own stack, hence, non-static variables

8条回答
  •  孤独总比滥情好
    2021-01-05 23:04

    "non-static variables exist in different locations" could not possibly be correct. In Java, you never directly get to know anything of "the stack". All of your class variables, static or instance, come from the heap. As a java developer, however, you don't really care about that.

    The only time you don't care about thread-safety is when your classes are immutable (don't change after construction) OR you aren't ever doing anything in threads. If your classes don't fall into these two categories, you need to think about making them thread-safe.

    The more immutability you can get into your designs, the easier the Threading issues are to reason about and overcome.

    Nrj has got the right idea.

提交回复
热议问题