1

I have an anonymous class which takes the iterated value from a collection as shown below. With this code, is that immediate variable in preserved within anonymous class? Or different threads can take same in value?

List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 20; i++)
    list.add(i);

for (final Integer in : list) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            Thread.sleep(1000);
            System.out.println(value + "," + in);
        }
    }).start();
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
vinayag
  • 384
  • 1
  • 4
  • 13
  • 1
    I don't find it particularly clear what you're asking. In this case, you are passing a different value of `in` to each of 20 threads. Is that what you wanted to know? – Dawood ibn Kareem Nov 06 '14 at 23:02
  • My question is that can two threads share same value? – vinayag Nov 06 '14 at 23:04
  • 1
    Also I thought the iteration on collection is implicitly converted into normal for loop with same variable for the iteration. So I was confused whether a new 'in' variable is created every time when we iterate on the collection. – vinayag Nov 06 '14 at 23:06
  • Yes, two threads can share the same value, but in your particular example, they don't. `in` is iterating through a list, in other words, it will take each value from the list in turn. The objects referenced by `in` don't need to be created each time, since they already exist in the list. – Dawood ibn Kareem Nov 06 '14 at 23:09

1 Answers1

3

Yes, each value of in is preserved in each of the Threads that is created. You can use a local variable in an anonymous inner class as long as it's declared final, or if you're using Java 8, if it's "effectively final" (not final but not changed).

rgettman
  • 176,041
  • 30
  • 275
  • 357