Sobes.tech
Junior — Middle

Explain how the synchronized keyword works in Java and its purpose when working with threads.

sobes.tech AI

Answer from AI

The synchronized keyword in Java is used to organize mutual exclusion when working with threads. It guarantees that at any given moment, only one thread can execute a block of code or a method marked with this keyword for the same monitor object.

When a thread enters a synchronized block or method, it acquires the monitor of the object (specified in the synchronized block or this for the method). Other threads attempting to enter the same synchronized block or method with the same monitor will be blocked until the first thread exits the block and releases the monitor.

This prevents race conditions and ensures correct access to shared resources.

Example:

public class Counter {
    private int count = 0;

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

    public synchronized int getCount() {
        return count;
    }
}

In this example, the increment and getCount methods are synchronized, so modifications and reads of the count variable will be thread-safe.

Explain how the synchronized keyword works in Java… - sobes.tech