开发者

ThreadLocal has strange behavior when used in the field of an anonymous Iterator

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?


OK, I figured it out (finally after hours of debugging). I was calling baz when another field was being initialized. My eyes just skipped over in the stack trace (many times). Ugh... Thanks for all the help though, particularly the observation that what I was seeing was expected behavior if those fields had not been initialized yet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜