如何使用ThreadLocal.withInitial使用Map类型初始化线程本地?

时间:2019-01-04 15:38:45

标签: java initialization thread-local

我正在尝试使用“ ThreadLocal.withInital”方法初始化Map类型的线程本地

我可以继续设置一个新的ThreadLocal并添加一个setter方法来进行初始化。但是我试图找到一种方法是否可以通过初始来完成。

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = new ThreadLocal<>();

预期输出:

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(<Hash-map that is set with a predefined date and a boolean>)

2 个答案:

答案 0 :(得分:1)

也许是这样:

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(() -> {
        Map<Date, Boolean> map = new HashMap<>();
        map.put(new Date(), true);
        //do other stuff...
        return map;
    });

答案 1 :(得分:1)

ThreadLocal.withInitial方法采用一个Functional参数,因此它可以是Lambda,如下所示:

private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(() -> {
    Map<Date, Boolean> map = new HashMap<>();
    map.put(new Date(), true);
    return map;
});