Labels

Monday, June 11, 2012

How JVM performs Thread Synchronization?

JVM associates a lock with an object or a class to achieve multithreading. A lock is like atoken or privilege that only one thread can "possess" at any one time. When a threadwants to lock a particular object or class, it asks the JVM.JVM responds to thread with alock maybe very soon, maybe later, or never. When the thread no longer needs the lock, itreturns it to the JVM. If another thread has requested the same lock, the JVM passes thelock to that thread. If a thread has a lock, no other thread can access the locked data untilthe thread that owns the lock releases it.The JVM uses locks in conjunction with monitors. A monitor is basically a guardian inthat it watches over a sequence of code, making sure only one thread at a time executesthe code. Each monitor is associated with an object reference. It is the responsibility of monitor to watch an arriving thread must obtain a lock on the referenced object.When the thread leaves the block, it releases the lock on the associated object. A singlethread is allowed to lock the same object multiple times. JVM maintains a count of thenumber of times the object has been locked. An unlocked object has a count of zero.

When a thread acquires the lock for the first time, the count is incremented to one. Eachtime the thread acquires a lock on the same object, a count is incremented. Each time thethread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.In Java language terminology, the coordination of multiple threads that must accessshared data is called synchronization. The language provides two built-in ways tosynchronize access to data: with synchronized statements or synchronized methods.The JVM does not use any special opcodes to invoke or return from synchronizedmethods. When the JVM resolves the symbolic reference to a method, it determineswhether the method is synchronized. If it is, the JVM acquires a lock before invoking themethod. For an instance method, the JVM acquires the lock associated with the objectupon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized methodcompletes, whether it completes by returning or by throwing an exception, the lock isreleased.Two opcodes, monitorenter and monitorexit are used by JVM for accomplishing this task.When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for thatobject, a count is incremented. Each time monitorexit is executed for the thread on theobject, the count is decremented. When the count reaches zero, the monitor is released.

No comments:

Post a Comment