Java Concurrency : Volatile & Atomic & ThreadLocal
Visibility Issue : using Volatile
Jun 30, 2021
Volatile make sure change on one thread will be visible immediately to other threads
Synchronization Issue : Compound Operations
Solution 1: use synchronized
synchronized (obj){
value ++
}
Solution 2: use AtomicInteger/AtomicXXX
AtomicInteger value = new AtomicInteger(0);
value.getAndIncrement()
ThreadLocal
Spring use XXContextHolder
which use ThreadLocal
- RequestContextHolder
- LocaleContextHolder
- DateTimeContextHolder
- SecurityContextHolder
- TransactionContextHolder