简体   繁体   English

在匿名迭代器的字段中使用时,ThreadLocal具有奇怪的行为

[英]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: 我有一个内部类,它使用类似于以下方法的方法实现Iterable:

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). 强烈地(对我而言),在某些情况下,在baz中foo的值为null,但是bar的值为0(初始化字段时不存在null指针异常)。 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. 同样,很奇怪的是,该字段首先为null,因为如果我打印堆栈跟踪,将调用ThreadLocal的set方法,该方法使用新构造的Foo对象设置其值,但这可能是另一个问题。

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. 当另一个字段正在初始化时,我正在打电话给baz。 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. gh ...不过,感谢您提供的所有帮助,尤其是观察到的是,如果尚未初始化这些字段,我所看到的就是预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM