reentrant synchronization

前端 未结 3 1978
一整个雨季
一整个雨季 2021-02-15 12:24

Can you tell me if following invocations are reentrant or not?

public class Foo {

  public synchronized void doSomething() {}

  public synchronized void doAnot         


        
3条回答
  •  爱一瞬间的悲伤
    2021-02-15 13:22

    That depends entirely on what other threads are accessing. Can another thread take over the CPU between those functions? Yes. Will there be a race condition? Depends on many factors.

    From what you posted foo.doSomething will be locked on foo, then released, then locked again upon entry to doAnotherSomething. So if another thread not locked on the same Too object tries to manipulate foo they will be able to do so between doSomething and doAnotherSomething. If everyone synchronized on the same Too object before manipulating the underlying foo object, then those two methods of foo will not have state manipulated between calls because the Too object method will block other threads until completion. Thus if you have a problem or not depends on your other accessors.

    There is no reentrance here from what you posted, but java is ok with reentrant synchronization as Amir posted.

提交回复
热议问题