# Synchronization — Advanced Java

Source: https://www.geekswithgeeks.com/en/advanced-java/adv-synchronization

> Fix race conditions and visibility bugs with synchronized and volatile, prefer atomics and ReentrantLock, and acquire locks in one order to avoid deadlock.

## The two problems

Shared mutable state causes **race conditions** (interleaved read-modify-write) and **visibility** bugs (one thread never sees another's write). `synchronized` fixes both for a block; `volatile` fixes visibility only.

## Prefer atomics & locks

`AtomicLong`, `AtomicReference` give lock-free updates via CAS. `ReentrantLock` adds `tryLock`, timeouts, and fairness that `synchronized` can't. `ReadWriteLock` allows many concurrent readers.

```java
private final AtomicLong hits = new AtomicLong();
public void record() { hits.incrementAndGet(); }

private final ReentrantLock lock = new ReentrantLock();
lock.lock();
try { /* critical section */ } finally { lock.unlock(); }
```

## Avoid deadlock

Deadlock needs two threads acquiring the same two locks in opposite order. Fix: always acquire locks in a single global order, or use `tryLock` with a timeout and back off.
