We can use instance of ThreadLocal class to transport information
within an application.
One use case is to transport security or login information within an
instance of ThreadLocal so that every method can access it.
Another use case is to transport transaction information across an
application, without using the method-to-method communication.
xxxxxxxxxx
public class ThreadSafeDateFormat {
//SimpleDateFormat is not thread-safe, so give one instance to each thread
private static final ThreadLocal<SimpleDateFormat> formatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy.MM.dd HHmm a"));
public static String formatIt(Date date) {
return formatter.get().format(date);
}
public static void main(String[] args) {
final String formatIt = ThreadSafeDateFormat.formatIt(new Date());
System.out.println("formatIt = " + formatIt);
}
}
https://www.javacodemonk.com/threadlocal-with-examples-usecases-in-java-3912002e