views:

324

answers:

4

I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?

The scenario is as follows

pulbic class SillyClassName {

    object moo;
    ...
    public void method1(){
        synchronized(moo)
        {
            ....
            method2();
            ....
        }
    }

    public void method2(){
        synchronized(moo)
        {
            doStuff();
        }
    }
}

Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?

I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.

A: 

In java, the synchronized keyword on a method basically synchronizes on the current object, so in effect it's doing what you suggest above implicitly.

You won't experience problems with synchronizing on one object in one method and then synchronizing on the same object in another method because, as you say, the current thread already holds the lock on that object.

Phill Sacre
A: 

No problems. In your example, (once you fix your code to get rid of the compile warnings that you'll get ;) ), the synchronization ensures that the blocks in method1 and method2 will not execute simultaneously.

That's kind of the point of synchronization. :)


Edit: Sorry, missed parts of your question, but Phill answered it. To summarize, a single thread cannot deadlock itself.

Jack Leow
+16  A: 

Synchronized blocks use reentrant locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect.

Leigh
A: 

No, the second method will not stop if called by first. No odd results will occur (except a slight overhead for checking lock. This wont matter much. Java 6 onwards, you have lock coarsening in the JVM - http://java.sun.com/performance/reference/whitepapers/6_performance.html )

For example, take a look at source code of java.util.Vector. There are lot of calls to other synchronized methods from within synchronized methods.

Satish Motwani