I have an inner class that implements Iterable with a method similar to the following:
public Iterator iterator() {
return new Iterator() {
Foo foo = fooThreadLocal.get();
int bar = foo._bar;
void baz() {
System.out.println("" + bar);
System.out.println("" + foo);
}
public Object next() {
baz();
...
}
}
}
Strangly (to me), in some cases, the value of foo is null inside baz, but the value of bar is 0 (no null pointer exception when the field is initialized). Also, it is strange that the field is null in the first place since if I print a stack trace there is a call to the set method of the ThreadLocal that sets its value with a newly constructed Foo object, but this may be a different problem.
Does anyone know what could be going on here?