randomDude randomDude - 1 year ago 64
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));
//some lines of code NOT involving myList
//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.

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

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 Source


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

to your Threading class and in your runnable add

public void run() {
  this.i = 1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download