Java Concurrency : Volatile & Atomic & ThreadLocal

Visibility Issue : using Volatile

Andrea Huang
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

--

--

Andrea Huang

我的Patrick是個6歲的小男孩。我想記錄下此時我想與他分享的感悟。雖然他此時未必能理解,但是等到適當的時機,他可以讀到來自媽媽當年的分享