小编thi*_*ket的帖子

在 Java 中使用 ThreadLocal 的良好实践

我有一个关于我应该如何使用ThreadLocal.

背景和情况

有几个单例对象用于ThreadLocal为每个线程创建一个副本。这个单例对象有一个函数foo()

public class SingletonA {
    protected static ThreadLocal<SingletonA> singleton = new ThreadLocal<SingletonA>() {
        @Override
        protected SingletonA initialValue() {
            return new SingletonA();
        }
    };

    private SingletonA() { ... }
    public static SingletonA getInstance() { return singleton.get(); }
    public static void remove() { singleton.remove(); }
    public static void foo() { ... }
}
Run Code Online (Sandbox Code Playgroud)

... 有 SingletonB、SingletonC 等等。

有一个单例存储库可以缓存ThreadLocal上面的单例。这个类也是一个ThreadLocal单例——

public class SingletonRepo {
        protected static ThreadLocal<SingletonRepo> singleton = new ThreadLocal<SingletonRepo>() { …
Run Code Online (Sandbox Code Playgroud)

java parallel-processing concurrency thread-local

5
推荐指数
1
解决办法
2056
查看次数