Site Search:

BasicSynchronizer.java

<Back


A synchronized method is a shorthand for a synchronized block that spans an entire method body, and whose lock is the object on which the method is being invoked. Every java object can implicitly act as a lock for purpose of synchronization. When thread A attempts to acquire a lock held by thread B, A must wait, or block, until B releases it. 

What is the problem of the following program? Why the threads in the program can access synchronized methods simultaneously? Shouldn't synchronized keyword guarantee exclusive access?
How to fix it?

public class BasicSynchronizer implements Runnable{
    private static SynchDemo demo = new SynchDemo();
    /*
    private SynchDemo demo = new SynchDemo();
    */
    public static void main(String ... args) {
        for(int i = 0; i < 5; i++) {
            Thread th = new Thread(new BasicSynchronizer());
            th.start();
        }
    }    
    public void run() {
        demo.sayHello();
    }
}

class SynchDemo {
    public synchronized void sayHello() {
        System.out.println(Thread.currentThread().getName() + " start");
        System.out.println(Thread.currentThread().getName() + " Hello");
        System.out.println(Thread.currentThread().getName() + " end");
    }
}

concurrency>javac BasicSynchronizer.java 
concurrency>java BasicSynchronizer
Thread-1 start
Thread-4 start
Thread-4 Hello
Thread-3 start
Thread-0 start
Thread-0 Hello
Thread-0 end
Thread-2 start
Thread-2 Hello
Thread-2 end
Thread-3 Hello
Thread-3 end
Thread-4 end
Thread-1 Hello
Thread-1 end
concurrency>


Hint: 
"A synchronized method is a shorthand for a synchronized block that spans an entire method body, and whose lock is the object on which the method is being invoked. "
What Objects act as the lock for synchronized method sayHello()?

Second Hint:
The SynchDemo objects act as the lock for synchronized method sayHello().
How many SynchDemo objects are created in the program?

Every time new BasicSynchronizer() is called, a new SynchDemo object is created, each thread hold a different lock, they didn't share the same lock.