how to create a thread local variable in java

Solutions on MaxInterview for how to create a thread local variable in java by the best coders in the world

showing results for - "how to create a thread local variable in java"
Sofia
06 Jan 2021
1public class MyDateFormatter {
2
3    private ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal = new ThreadLocal<>();
4
5    public String format(Date date) {
6        SimpleDateFormat simpleDateFormat = getThreadLocalSimpleDateFormat();
7        return simpleDateFormat.format(date);
8    }
9    
10    
11    private SimpleDateFormat getThreadLocalSimpleDateFormat() {
12        SimpleDateFormat simpleDateFormat = simpleDateFormatThreadLocal.get();
13        if(simpleDateFormat == null) {
14            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
15            simpleDateFormatThreadLocal.set(simpleDateFormat);
16        }
17        return simpleDateFormat;
18    }
19}
20