If a class has an inner class and the inner class runs a thread, do the inner class threads share the same fields of the outer class with one another?

Viewed 98

Basically, if I have the code:

public class Outer { 
   public int counter = 0;
   public void makeNewThread() {
      Thread t1 = new Thread(new Inner());
      t1.start();
   }

   private class Inner implements Runnable {
      public void run() { //do stuff involving counter... }
   }

}

Everytime makeNewThread() is called, will each thread have their own version of counter, or will they all share the same version of counter? I would assume they would all share the same version since it's an inner class, but each thread has their own stack so I'm not sure.

2 Answers

They will share the same counter.

If you have only a single instance of Outer, you will have only a single instance of counter. All the threads will share it.

Important! Validate concurrency and visibility issues accessing the counter from different threads. Most probably you need to use AtomicInteger instead of "int" or wrap all the access code (for both write and read operations) into a synchronize block.

Related