Concurrent access to static methods

前端 未结 6 1871
面向向阳花
面向向阳花 2020-12-14 01:45

I have a static method with the following signature:

public static List processRequest(RequestObject req){
  // process the request obje         


        
6条回答
  •  青春惊慌失措
    2020-12-14 02:39

    I see a lot of answers but none really pointing out the reason.

    So this can be thought like this,
    Whenever a thread is created, it is created with its own stack (I guess the size of the stack at the time of creation is ~2MB). So any execution that happens actually happens within the context of this thread stack.
    Any variable that is created lives in the heap but it's reference lives in the stack with the exceptions being static variables which do not live in the thread stack.

    Any function call you make is actually pushed onto the thread stack, be it static or non-static. Since the complete method was pushed onto the stack, any variable creation that takes place lives within the stack (again exceptions being static variables) and only accessible to one thread.

    So all the methods are thread safe until they change the state of some static variable.

提交回复
热议问题