Java - Thread Synchronization

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.

In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.

Generally critical sections of the code are usually marked with synchronized keyword. Locks are used to synchronize access to a shared resource. A lock can be associated with a shared resource.

Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.

At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.

A lock thus implements mutual exclusion.
The object lock mechanism enforces the following rules of synchronization:

A thread must acquire the object lock associated with a shared resource, before it can enter the shared resource. The runtime system ensures that no other thread can enter a shared resource if another thread already holds the object lock associated with the shared resource. If a thread cannot immediately acquire the object lock, it is blocked, that is, it must wait for the lock to become available.
  • When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain accessto the shared resource.
Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class denotes this unique Class object. The class lock can be used in much the same way as an object lock to implement mutual exclusion.

There can be 2 ways through which synchronized can be implemented in Java:
  • synchronized methods
  • synchronized blocks

Synchronized statements are same as synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock on the object/class referenced in the synchronized statement.

Related Post:-

People who read this post also read :



0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More