Java.Multithreading.What are the different types of synchronization in Java?

🧠 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:

ToolDescription
CountDownLatchWaits until a fixed number of signals
CyclicBarrierWaits for all threads to reach a point
SemaphoreControls access to a limited resource
ExchangerTwo threads swap data
PhaserDynamic barrier for multiple phases

✅ These provide high-level thread synchronization mechanisms


🧠 Summary Table

TypeTool/KeywordBest For
Intrinsic Synchronizationsynchronized, wait/notifyBasic mutual exclusion
Explicit LockingReentrantLock, etc.Fine-grained control
Lock-FreeAtomicInteger, etc.High-performance atomic ops
Visibility-OnlyvolatileLightweight flag sharing
Coordination UtilitiesCountDownLatch, etc.Thread orchestration & control
This entry was posted in Без рубрики. Bookmark the permalink.