What is synchronized in Java?

In Java, the term synchronized is used to control access to a particular resource by multiple threads. When a method or block of code is declared as synchronized, it ensures that only one thread can access that resource at a time, thereby preventing thread interference and memory consistency errors. This is particularly important in multi-threaded applications where shared resources are accessed concurrently.

Example of Synchronized Method

public class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } }

Example of Synchronized Block

public class Counter { private int count = 0; public void increment() { synchronized (this) { count++; } } public int getCount() { synchronized (this) { return count; } } }

synchronized multi-threading Java synchronization thread safety Java programming