I'm trying to initialise a thread-local of type Map using "ThreadLocal.withInital" method
I can proceed with setting a new ThreadLocal and adding a setter method to proceed with the initialisation. But I'm trying to find a way whether this can be done via initial.
private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = new ThreadLocal<>();
Expected Output:
private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(<Hash-map that is set with a predefined date and a boolean>)
Maybe this:
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 method takes a Functional parameter, so it can be a Lambda, like this:
private static final ThreadLocal<Map<Date, Boolean>> dateBooleantl = ThreadLocal.withInitial(() -> {
Map<Date, Boolean> map = new HashMap<>();
map.put(new Date(), true);
return map;
});
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.