Sobes.tech
Junior — Middle

Can you explain the purpose and working principle of the synchronized keyword in Java?

sobes.tech AI

Answer from AI

The synchronized keyword in Java is used to control access to shared resources in a multithreaded environment. It ensures that only one thread can execute a specific block of code or method at a time, preventing race conditions and ensuring data integrity.

Working principle:

  • When a thread enters a synchronized block or method, it acquires the monitor (lock) of the object.
  • Other threads attempting to enter the same synchronized block or method on the same object will wait until the monitor is released.
  • After exiting the synchronized block, the monitor is released, and the next waiting 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 to prevent multiple threads from changing the count variable simultaneously.

Can you explain the purpose and working principle of… - sobes.tech