Home  >  Article  >  Synchronize twice on the same object?

Synchronize twice on the same object?

WBOY
WBOYforward
2024-02-06 11:45:09546browse
Question content

I would like to know if in java, if I synchronize twice on the same object, there will be any strange behavior?

The scene is as follows

pulbic class SillyClassName {

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

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

Both methods use this object and synchronize on it. When the first method calls the second method, will the second method stop because it is locked?

I don't think so since it's the same thread, but I'm not sure if any other weird results are happening.


Correct answer


Reentrant

Synchronized blocks use reentrant locks, which means that if a thread already holds a lock, it can reacquire it without issue. So your code will work as you expect.

See the Java Tutorial at the bottom of the page Intrinsic Locks and Synchronization.

Quote as of January 2015...

I think we have to use a reentrant lock to accomplish what you want to do. Here is a snippet from http: //docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html.

Although I haven't tried it, I think if you want to do the above, you have to use a reentrant lock.

The above is the detailed content of Synchronize twice on the same object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete