vinayag
vinayag

Reputation: 404

Final variables within anonymous classes

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();
}

Upvotes: 1

Views: 61

Answers (1)

rgettman
rgettman

Reputation: 178333

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).

Upvotes: 3

Related Questions