Thread Synchronization in Java using synchronized/lock
Why Synchronization needed?
Normally Multiple threads run asynchronously in a single program which provides expected results if there is no shared resource. But in some cases it’s possible that more than one thread can access the shared resource (That is, more than one thread access the same object of a class) at the given time and in such cases it may provide inconsistent results.
For example in ticket reservation system where 2 passengers are trying to book seats at the same time for same source and destination and both noticed 1 seat is available to book . Passenger1 books 1 seat and Passenger2 books 1 seat and both got successful message for booking. Totally 2 seats got booked whereas only 1 seat is available . In this example passenger 1 is Thread1 and passenger 2 is Thread2 when they try to access shared resource (Seats) in ticket reservation system asynchronously, Thread1 &2 modifies the state of object inconsistently.
Example program which produces inconsistent result when implemented without synchronized


Output

This inconsistent modification on the state of java object can be solved by a synchronization mechanism in which when Thread1 is accessing the state of object, another thread(Thread2) will wait to access the same object at a time until Thread1 completes its operation on shared resource object.
Ways to achieve Synchronization in Java
- Synchronized Method
- Synchronized Block
Synchronized Method
Example program which produces correct result when implemented with synchronized method


Output

Synchronized Block
Example program which produces correct result when implemented with synchronized block


Output

Lock
Lock works similar to Synchronized blocks/methods , Locks allow more flexible structuring of synchronized code , more methods are available based on the need we can use those methods. Here lock() method is used to get a lock (monitor) on the object and unlock() is used to release lock which needs to be present in finally block.
Example program which produces correct result when implemented with lock


Output
