randomDude randomDude - 25 days ago 6
Java Question

List populated in different thread appears empty in caller thread - Java

My code basically goes like this:

//in Main Thread: (myList is a volatile field)
myList = new ArrayList<myClass>();
Thread myThread = new Thread(new MyCustomRunnable(myList));
myThread.start();
//some lines of code NOT involving myList
myThread.join();
//myList appears empty here even though I can see that the list has been populated
//in the other thread


Is there a reason for this behavior? Like I said, i can see in the debugger that the list has been populated in the called thread, but these changes don't appear in the caller thread after the join() method. MyCustomRunnable also declares the ArrayList as a volatile field, assigned by the constructor.

UPDATE:
Ok, I made a simpler program, replacing the ArrayList with a simple Integer and the results are the same...

public class Threading {
private volatile static Integer i = 0;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new MyCustomRunnable(i));
t.start();

t.join();
System.out.println(i); //prints '0', I expected '1'
}
}

public class MyCustomRunnable implements Runnable {
private volatile Integer i;

public MyCustomRunnable(Integer i) {
this.i = i;
}

public void run() {
this.i = 1;
}

}


Why isn't the Integer's value updated in the main Thread?

Answer

Add

public static void setI(int i) {
  Threading.i = i;
}

to your Threading class and in your runnable add

public void run() {
  this.i = 1;
  Threading.setI(1);
}