如何使用 ThreadLocal.withInitial 初始化 Map 类型的局部线程?
How to initialise a thread-local with type Map using ThreadLocal.withInitial?
我正在尝试使用 "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>)
也许是这样:
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;
});
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;
});
我正在尝试使用 "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>)
也许是这样:
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;
});
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;
});