user1275375
user1275375

Reputation: 1391

locks on java synchronized methods

I am trying to write a java program with threads using synchronized methods. But iam not able to understand how can i display that already a thread is running when another thread invokes synchronized method in java. Can any one explain with simple example

Upvotes: 1

Views: 500

Answers (2)

Andrii Polunin
Andrii Polunin

Reputation: 1306

If I understand you correctly you want to print a message when a thread tries to invoke a synchronized method while another thread is already executing it. You cannot do this with synchronized methods or blocks but you can do it using java.util.concurrent.locks.Lock interface instead. The method you need is tryLock(). You can do something like this:

public class Test1 {
    private Lock lock = new ReentrantLock();

    // ...

    public void method() {
        if (lock.tryLock()) {
            try {
                // you successfully acquired the lock, do you logic here
            } finally {
                lock.unlock();
            }                
        } else {
            // lock is hold by another thread
            System.out.println("cannot acquire a lock");
        }
    }
}

You can easily evolve this example to print which thread exactly holds the lock if you wish.

Upvotes: 0

assylias
assylias

Reputation: 328855

Here is a contrived example which shows the interleaving and blocking process. On my machine it prints:

Thread[Thread-0,5,main] is going to call the synchronized method
Thread[Thread-1,5,main] is going to call the synchronized method
Thread[Thread-0,5,main] is in the synchronized method
Thread[Thread-0,5,main] is exiting the method
Thread[Thread-1,5,main] is in the synchronized method
Thread[Thread-1,5,main] is exiting the method

You can see that only one thread enters the synchronized block while the other waits.

public class Test1 {

    public static void main(String[] args) throws Exception {
        final Test1 test = new Test1();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread() + " is going to call the synchronized method");
                test.method();
            }
        };
        new Thread(r).start();
        new Thread(r).start();
    }

    public synchronized void method() {
        System.out.println(Thread.currentThread() + " is in the synchronized method");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        System.out.println(Thread.currentThread() + " is exiting the method");
    }
}

Upvotes: 3

Related Questions