Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reentrant synchronization

Tags:

java

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

public class Foo {

  public synchronized void doSomething() {}

  public synchronized void doAnotherSomething() {}
}

public class Too {

  private Foo foo;

  public synchronized void doToo() {
    foo.doSomething();
    //...other thread interfere here....
    foo.doAnotherSomething();
  }

}

are 2 continuous invocations in method doToo() reentrant? I'm not sure about this case since foo.doSomething() method acquire and release the intrinsic lock, no nested synchronization between 2 invocations. Is there situation that other thread might interfere between 2 invocations?

like image 928
MinhHoang Avatar asked Aug 31 '12 16:08

MinhHoang


2 Answers

First of all, regarding reentrant locks in Java:

Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same monitor object.

Taken from here.

The two consecutive calls you described (in doToo) will not be interfered unless another object has a reference to Too's private Foo, since, to access foo, one needs to lock Too. However, the calls do not invoke reentry as the locks are acquired and released for every call. They would be reentrant if doSomething called doAnotherSomething or vice versa.

like image 94
Amir Rachum Avatar answered Oct 21 '22 10:10

Amir Rachum


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.

like image 23
Pyrce Avatar answered Oct 21 '22 10:10

Pyrce