tana
tana

Reputation: 585

Value in list is not updated by thread

I tried to update value in a list by thread,
but it does not working for me.
Below is my code, please point what i am wrong. Thanks.

// List of Integer values
public static volatile ArrayList<Integer> intList = new ArrayList<Integer>();

public static void main(String... args) {
    intList.add(11);

    Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            // Loop and increase value of a list of integer
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (this) {
                    for (Integer item : intList) {
                        System.out.print("thread 1: " + item);
                        item++; //increase value
                        System.out.print(" -> " + item + "\n");
                    }
                }
            }
        }
    });
    thread1.start();
}

Output:
thread 1: 11 -> 12
thread 1: 11 -> 12
thread 1: 11 -> 12
thread 1: 11 -> 12
thread 1: 11 -> 12
=> value is not changed when the loop start, it still 11 every time of beginning of loop.
What's wrong?

Upvotes: 1

Views: 167

Answers (1)

riccardo.cardin
riccardo.cardin

Reputation: 8353

The problem is in this line of code:

item++; //increase value

The JVM is applying autoboxing to object item, creating an int primitive value, augmenting it by 1, and then creating a new Integer Object. So, you are not modifying the object inside your list.

Upvotes: 4

Related Questions