Sobes.tech
Junior — Middle

Can you explain how thread synchronization is implemented using the synchronized keyword in Java?

sobes.tech AI

Answer from AI

The synchronized keyword in Java is used to ensure thread synchronization and prevent concurrent access to critical sections of code, helping to avoid race conditions.

Working principle:

  • When a thread enters a block or method marked synchronized, it acquires the monitor (lock) of the object.
  • Other threads attempting to enter the same synchronized block or method with the same monitor will be blocked until the lock is released.
  • After exiting the synchronized block, the monitor is released, and another thread can enter.

Example:

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Here, the increment method is synchronized, so even if multiple threads call it simultaneously, the increment of count will be atomic.

You can also synchronize blocks of code:

public void someMethod() {
    synchronized(this) {
        // critical section
    }
}

Thus, synchronized guarantees that only one thread at a time executes the protected code, ensuring data correctness in multithreaded access.

Can you explain how thread synchronization is… - sobes.tech