When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issue. For example if multiple threads try to write within a same file then they may corrupt the data because one of the threads can overrite data or while one thread is opening the same file at the same time another thread might be closing the same file. The problems arise when multiple threads access the same resources - the same memory (variables, arrays, or objects), systems (databases, web services etc.) or files. To prevent race conditions from occurring you must make sure that the critical section is executed as an atomic instruction. That means that once a single thread is executing it, no other threads can execute it until the first thread has left the critical section. Synchronization in Java will only be needed if shared object is mutable.

 So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.

In Java, two synchronization strategies are used to prevent thread interference and memory consistency errors:

Synchronized Method: Includes the synchronized keyword in its declaration. When a thread invokes a synchronized method, synchronized method automatically acquires the intrinsic lock for that method's object and releases it when the method returns, even if that return was caused by an uncaught exception.

Synchronized Statement: Declares a block of code to be synchronized. Unlike synchronized methods, synchronized statements should specify the objects that provide the intrinsic lock. These statements are useful for improving concurrency with fine-grained synchronization, as they enable the avoidance of unnecessary blocking.

The synchronized keyword can be used to mark four different types of blocks:

1. Instance methods (each instance has its synchronized methods synchronized on a different object)

2. Static methods (synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to)

3. Code blocks inside instance methods

4. Code blocks inside static methods




3) synchronized keyword involve locking and unlocking. Before entering into synchronized method or block thread needs to acquire the lock, at this point it reads data from main memory than cache and when it release the lock, it flushes write operation into main memory which eliminates memory inconsistency errors.

Important points of synchronized keyword in Java













13. According to the Java language specification you can not use Java synchronized keyword with constructor.


