40. How does thread synchronization occurs inside a monitor ? Explain

What levels of synchronization can you apply? What is the difference between synchronized method and synchronized block?

In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in method level (coarse grained lock – can affect performance adversely) or block level of code (fine grained lock). Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, dummy objects can be created to implement block level synchronization.

The block level is more efficient because it does not lock the whole method.

class MethodLevel {
// shared among threads
SharedResource x, y;

public synchronized void method1() {
// multiple threads can't access
}

public synchronized void method2() {
// multiple threads can't access
}

public void method3() {
// not synchronized
// multiple threads can access
}
}


class BlockLevel {
// shared among threads
SharedResource x, y;
// dummy objects for locking
Object xLock = new Object(), yLock = new Object();

public void method1() {
synchronized (xLock) {
// access x here. thread safe
}
// do something here but don't use
SharedResource x, y;
synchronized (xLock) {
synchronized (yLock) {
// access x,y here. thread safe
}
}
// do something here but don't use
SharedResource x, y;
}
}


The JVM uses locks in conjunction with monitors. A monitor is basically a guardian who watches over a sequence of synchronized code and making sure only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object.

Why synchronization is important? Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors.

The disadvantage of synchronization is that it can cause deadlocks when two threads are waiting on each other to do something. Also synchronized code has the overhead of acquiring lock, which can adversely the performance.



No comments:

Post a Comment