简体   繁体   中英

ThreadLocal with Supplier for static fields

I have a bunch of static utility fields and I am wondering if I should use ThreadLocal for all of these fields.

version 1 (with ThreadLocal Supplier):

private static final ThreadLocal<DateTimeFormatter> TIME_FORMAT = 
ThreadLocal.withInitial(() -> DateTimeFormatter.ofPattern("HH:mm:ss"));

version 2 (normal):

private static final DateTimeFormatter TIME_FORMAT_2
 = DateTimeFormatter.ofPattern("HH:mm:ss");

What are the consequences, benefits, pitfalls when using version 1 instead of version 2. Which one should I prefer and why (memory, performance)?

ThreadLocal is used to have different instances for different threads.
Since DateTimeFormatter is thread safe, there is no advantage of version 1.
Use version 2.

Even if is thread safe, there could be an advantage in general, because with a ThreadLocal you can imitate a cache , so within the thread the instance is only created once and not for every call.

So I think the memory, performance will be better when using ThreadLocal . The DateTimeFormatter is only an example here to illustrate the general useness of a ThreadLocal but it could also be a regular expression (coming from Pattern.compile() ) or anything else which may be useful for caching.

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