Supposing I have the following
public class Foo {
private Map<Integer,SomeObject> myMap;
public Foo() {
this.myMap = new HashMap<Integer,SomeObject>();
}
private class Runner implements Runnable {
public void run() {
SomeObject someObj = new SomeObject();
Foo.this.myMap.put(10,someObj);
//'soObj' will always be null upon retrieval later...
}
}
}
If I create a thread with a Runnable of type ‘Runner’ and start the thread, it will run.
In the run method, I simply create an instance of ‘SomeObject’ and place it in the map of the outer class.
However, when I attempt to get a value from ‘myMap’ later on, the ‘SomeObject’ instance will always be null. I can’t understand why as I have placed a reference into the map ‘myMap’ which still lives on in the heap after the thread finishes. Is there a way around this?!
Thanks very much
It could be a problem with the way your objects are instantiated. It should be: