简体   繁体   中英

ThreadLocal initialValue() called multiple times per thread. why?

We see an issue due to ThreadLocal's initialValue() being called multiple times.

private static class MonMetricsTLS extends ThreadLocal<IMonitor> {
    public MonMetricsTLS(MetricConfig config) {
        this.config = config;
        Timer timer = new Timer(true);
    }

    @Override
    protected IMonitor initialValue() {
            IMonitor mon = new MonitorImpl(config);
            timer.schedule(new SenderTimerTask(mon), config.senderPeriodMs(), config.senderPeriodMs());
            return mon;
    }
}

Between first and second calls timer can go bad and we get illegalstateexception in schedule().

Why is it getting called multiple times per thread?

This looks like you are using the same Timer object in more than one thread. You should move the new Timer() into initialValue() . Only then you can be sure to have a unique Timer object per thread. And guessing from your code, config is immutable so you can pass this into the timer. You then only create one MonMetrics and reuse it in all threads.

It looks like java thread local doesn't guarantee initialValue() will be called exactly once! So it is best to assume it can be called any number of times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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