Sobes.tech
Junior — Middle

In what cases is the synchronized modifier used in the code?

sobes.tech AI

Answer from AI

The synchronized modifier in Java is used to ensure thread safety when working with shared resources in a multithreaded environment. It guarantees that only one thread at a time can execute a synchronized block or method, preventing race conditions.

It is used in cases where:

  • You need to protect a critical section of code that modifies shared data.
  • You need to ensure the atomicity of operations.
  • You want to avoid concurrent access to an object or method from multiple threads.

Example:

public class Counter {
    private int count = 0;

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

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

Here, the increment and getCount methods are synchronized to prevent incorrect modification and reading of the count variable from different threads.