🧠 1. Intrinsic (Built-in) Synchronization
This is the most commonly used type of synchronization in Java, based on monitors.
A. Synchronized Method
public synchronized void increment() {
// Only one thread at a time can execute this method
}
Locks on the current object (this)
For static methods, it locks on the class object (ClassName.class)
B. Synchronized Block
public void increment() {
synchronized (this) {
// Critical section
}
}
You can lock on any object (this, a field, or any shared object)
Useful when you want partial synchronization
🔐 2. Explicit Synchronization (Lock API)
Java provides more advanced synchronization using java.util.concurrent.locks
A. ReentrantLock
Lock lock = new ReentrantLock();
lock.lock();
try {
// Critical section
} finally {
lock.unlock();
}
Manual lock management
Supports fairness, tryLock(), and interruptible locks
B. ReentrantReadWriteLock
ReadWriteLock rwLock = new ReentrantReadWriteLock();
rwLock.readLock().lock();
rwLock.writeLock().lock();
Allows multiple readers but only one writer
Improves performance in read-heavy scenarios
⚡ 3. Atomic Variables (Lock-Free Synchronization)
From java.util.concurrent.atomic package
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
Lock-free
Extremely fast
Useful for simple shared counters and flags
👀 4. Volatile Keyword (Visibility Only)
volatile boolean flag = false;
Guarantees visibility, but not atomicity
Ensures writes to the variable are immediately visible to other threads
Lightweight compared to full synchronization
🛏️ 5. Wait/Notify Mechanism
Used for thread coordination inside synchronized blocks:
synchronized (lock) {
while (!condition) {
lock.wait(); // releases lock and waits
}
// do something
lock.notify(); // wakes up one waiting thread
}
Used when one thread needs to wait for a condition
Always used inside a synchronized block
⚙️ 6. Thread Coordination Tools
These are part of java.util.concurrent:
| Tool | Description |
|---|---|
CountDownLatch | Waits until a fixed number of signals |
CyclicBarrier | Waits for all threads to reach a point |
Semaphore | Controls access to a limited resource |
Exchanger | Two threads swap data |
Phaser | Dynamic barrier for multiple phases |
✅ These provide high-level thread synchronization mechanisms
🧠 Summary Table
| Type | Tool/Keyword | Best For |
|---|---|---|
| Intrinsic Synchronization | synchronized, wait/notify | Basic mutual exclusion |
| Explicit Locking | ReentrantLock, etc. | Fine-grained control |
| Lock-Free | AtomicInteger, etc. | High-performance atomic ops |
| Visibility-Only | volatile | Lightweight flag sharing |
| Coordination Utilities | CountDownLatch, etc. | Thread orchestration & control |