Tutorial by Examples

public static class ThreadLocalExample { private static final ThreadLocal<SimpleDateFormat> format = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd_HHmm")); public String formatDate(Date date) { return format.get().format(date); ...
Java ThreadLocal is used to create thread local variables. It is known that threads of an Object share it’s variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization,ThreadLocal allows us to create variables which are local to...
In this example we have only one object but it is shared between/executed on different threads. Ordinary usage of fields to save state would not be possible because the other thread would see that too (or probably not see). public class Test { public static void main(String[] args) { ...

Page 1 of 1