简体   繁体   中英

Does a synchronized objects handle pass to a called function in Java?

So lets say I have this code:

public void bar(){
  synchronized(foo){foo.remove(0)}
}

public void doStuff(){
  synchronized(foo){
     bar()
  }
}

Will synchronized realize that the current chain I'm in has this lock and inherit it or will it deadlock?

The lock you get from a synchronized block is reentrant . This will not dead-lock, a thread can acquire a lock on the same object multiple times.

See Intrinsic Locks and Synchronization .

As Mat said it won't dead lock.

How i see it as

that this lock mechanism isn't dependent over method call but on control flow. How a single thread is executing statements and when a thread encounters a synchronized block then it ask for the lock of the object in the synchronized signature.

If it has it then it enters else will wait in the lock pool of the object until gets notified.

thread which executed doStuff() already carried the lock so thats why no case of deadlock

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM