Thread synchronization (thread safety) in java – example

The objective of thread synchronization is to ensure that when more threads want access to a single resource,only one thread can access it at any given time. we can use thread synchronization to manage the execution of threads with synchronized methods and synchronized blocks.


Thread synchronizationA non-synchronized method example :

Thread synchronization

The below class online_Movie_Ticket_Booking  is not a synchronized  class. so more threads  can access and executes the method (ticket_availability) simultaneously.Because of that ,it produces unexpected results.

From the above code, the available tickets are 3 and reserved to the first person . So now the available tickets are 0 , but in the output it is 3 (wrong). To prevent data inconsistency problems , we need to use the synchronization  techniques.



Thread synchronization Synchronized methods (for thread synchronization) :

Thread synchronization

Thread synchronization Declare one or more methods in a class as a synchronized with the synchronized keyword. It will lock the other threads ,when any thread is already executing in the particular method.

Thread synchronization If any class contains more synchronized methods , only one synchronized method can be executing at one time , because that method has set the lock that prevents any other synchronized method from starting. But the non- synchronized methods will execute simultaneously.




Thread synchronization Synchronized blocks/statements (for thread synchronization) :

Thread synchronization

Thread synchronization If very few lines of the code required synchronization then declaring entire method as the synchronized is not recommended. We have to declare those few lines of the code inside synchronized block. This approach reduces waiting time of the Thread and improves performance of the system.

Thread synchronization Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock .

Thread synchronizationThe synchronized method or statement  increases waiting time of the threads and it effect performance of the system.
Thread synchronizationHence if there is no specific requirement , it is not recommended to use synchronized keyword.

Related Posts :
Threads in java ( Multithreading ) with an example
   [will not be published]

^ <