JavaAdvanced#concurrency

What is a ThreadLocal and when would you use it?

ThreadLocal provides a variable with a separate copy for each thread accessing it, useful for per-thread context like database connections, user sessions, or date formatters without synchronization overhead.

Example
ThreadLocal<SimpleDateFormat> formatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
formatter.get().format(new Date());

Related Questions

1
JavaIntermediate#concurrency

What is the difference between Thread.sleep() and Object.wait()?

Open
2
JavaAdvanced#concurrency

What is the difference between ReentrantLock and synchronized?

Open
3
JavaAdvanced#concurrency#java8

What is a CompletableFuture and how does it improve async programming?

Open