3

I have a method as follows:

public static void method() {

int i = 0;
i = i + 1;

}

I have an int variable inside a static method. And the method is accessed by several Threads.
My questions are:

  1. Does the i variable go to race condition?
  2. What if the method accessed in spring web application and accessed by multiple users at a same time?
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Lakmal Vithanage
  • 2,767
  • 7
  • 42
  • 58

2 Answers2

10

If the variable is declared within the method, then it lives in the stackframe provided for a single invocation of the method. The stackframe is accessed only by the thread invoking the method. There is no race condition in the posted example, every invocation of the method gets its own copy of the variable. You need shared state in order to have a race condition.

These stackframes are the things that pile up when executing a recursive method, and take up stack space until at some point the system runs out of space and a stackoverflow error occurs, because the recursion results in more and more stackframes getting allocated, while none of the method calls get a chance to complete (which would free up their stack space).

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

No, There is no race condition with the local variable of static method. Because for each envocation of method either static or non-static there will be seperate memory in stack, so that local variable of this static method will be seperate for each thread, and no race condition will be there.