Sunday, May 16, 2010

Simplifying the Locking Mechanism in Threads

synchronized(lockObject)
{
    // do the job
}

This is one of the ways to acquire a lock on an object and then do the work in a code block with exclusive rights. Synchronization is already explained with another blog 'Mystery of Synchronized Keyword'. 

Here the question is that why we take the lock on an Object, not on current thread. Answer is fairly simple. Whenever you want to secure the admission to any premises, you never apply a lock on yourselves but you will put a lock on some other object, like on door. So the thread is the 'actor' (you) who want to perform some work in a code block (premises). Here the thread want a exclusive access on a code block where it want to work. Now procedure to have exclusive access is to have a lock for code block, so that only the current thread can have access rights to it. Here thread needs any object (door), like lockObject in above example, to have lock on the code block. 

Further we need to understand that how thread get lock using an object. To understand the story under the hood, consider that every Object is having a state within it which shows that whether any thread has lock on this object or not. Whenever any thread request the lock on any object, object checks whether its lock property is already set or not. If not, it set its property for current thread otherwise it refuse to give the lock, ask the current thread to wait till previous thread release the lock and put the thread in queue. Once the previous thread release the lock, and hence unset the property, Object picks the next thread from queue and set the lock property for it. As soon as thread get the object property set for it, it get the rights to enter in code block and to execute it.

Another example is like more than one painters are painting an house. Now painting of one room needs that only one painter works in it at a time for good output. Like first one painter should apply the putty on the wall, then the next one should apply the primer and paint and so on. To ensure that everyone follow this, painter decide to lock the door of the room whenever anyone enter inside for the work. So as soon as putty man enters the room, he locks the door from inside. When other come for the work, they find the door locked and hence wait for their turn. As soon as, first man finishes his work, he opens the door and the next painter waiting in the queue gets the access to room. 

Runtime environment of Java ensure all of this processing i.e. it puts the current thread to wait state till it gets access on current object lock property and put it back to execution after getting the property set for it. 


No comments:

Post a Comment