Race Condition with Static Class?

后端 未结 3 1652
孤独总比滥情好
孤独总比滥情好 2020-12-06 07:52

Let\'s say I have a static class with a static method.

Multiple threads can call this static method concurrently.

Is there a potential for a race condition u

3条回答
  •  长情又很酷
    2020-12-06 08:29

    First off, a method is simply a piece of code residing at an address. Each thread calling a method will have a copy of that method and its local variables on its own private stack. So in case a, provided there are no other catches, it should be thread-safe.

    Case b depends on a lot of factors:

    • are you actually accessing those member variables?
    • how are you accessing them: only reads, reads + writes, etc.
    • what kind of member variables: data structures, single values.
    • do you have any synchronization in place?
    • etc.

    Generally though, assuming you do access the class members, it should not be considered thread-safe.

提交回复
热议问题