Local variables in static method and thread safety

前端 未结 3 1454
悲哀的现实
悲哀的现实 2021-02-01 05:32

I have a question about variable scope.

For example:

class A {
    private static void test() {
        // do something with local variables
    }
}
         


        
3条回答
  •  悲哀的现实
    2021-02-01 06:08

    For number 1, I don't know what test() does, so I cannot answer. If they modify some static variable of the class A, then it may not be thread safe. If both threads along the way are given reference to the same object, depending on how the object is defined, it might not be thread safe.

    For number 2, local variables are in the stack of each thread (or at least conceptually like that), so there is no worry about the local variables being modified by the other threads.

提交回复
热议问题