Sobes.tech
Junior — Middle

In which situations should the synchronized keyword be used in a programming language to ensure thread safety?

sobes.tech AI

Answer from AI

The synchronized keyword in Java is used to ensure thread safety when accessing shared resources concurrently. It guarantees that only one thread can execute a specific block of code or method at a time.

Use synchronized in the following situations:

  • When modifying shared data or states that can be accessed by multiple threads.
  • When working with shared resources, such as collections, files, databases.
  • To prevent data races and ensure atomicity of operations.

Example of using synchronized:

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 concurrent modification and reading of the count variable from different threads.