title: Local variables and thread safety
body: <p>In Java if you have the following method:</p>
  
  <pre><code>public int foo(int n) {
      int i=n;
      i = i+1; i = i-1;
      return i;
  }
  </code></pre>
  
  <p>So in a sequential program the return value will always be the same as the input.</p>
  
  <p>ie: <code>j == foo(j)</code></p>
  
  <p>However if you have multiple threads call foo, can you guarantee that <code>j==foo(j)</code>?</p>
  
  <p>I would say yes that it is guaranteed, because <code>i</code> is a local variable, and each thread has its own stack so <code>i</code> will be a different memory location for each thread.</p>
  
  <p>I would say you couldn't guarantee that <code>j==foo(j)</code> if <code>i</code> is a instance variable:</p>
  
  <pre><code>private int i;
  public int foo(int n) {
      i=n;
      i = i+1; i = i-1;
      return i;
  }
  </code></pre>
  
  <p>Because the threads can interleave and the value of <code>i</code> can change half way through a thread executing the method, or one thread can increment <code>i</code>, but before it gets chance to decrement it, another thread returns with it's input incremented twice and decremented only once.</p>