warren
warren

Reputation: 583

speed of nested synchronized

Is a nested synchronized block faster to get into than a normal synchronized block? Or for example, which of the following routines is faster:

void routine1(SyncClass a) {
  a.syncMethod1();
  a.syncmethod2();
  a.syncMethod1();
}

void routine2(SyncClass a) {
  synchronized(a) {
    a.syncMethod1();
    a.syncmethod2();
    a.syncMethod1();
  }
}

The methods are synchronized. I am considering the use of a thread safe object in a situation where thread safety is not needed. So level of concurrency is not affected.

Also, is the answer platform dependant?

Upvotes: 3

Views: 282

Answers (2)

warren
warren

Reputation: 583

It appears that the answer is yes, as per comments left on the question. But with two caveats.

1) Due to fewer opportunities for parallel execution, threads may wait on each other more often.

2) The compiler may optimize this way automatically.

Upvotes: 0

cheeken
cheeken

Reputation: 34655

You're better off synchronizeding the smallest code elements you can, performance-wise, regardless of the platform.

Wrapping a number of synchronized calls in a synchronized block will reduce concurrency (and so, performance). Only do it if you need that particular sequence of calls to be synchronized.

If you're concerned about the performance impact besides that which is derived from concurrency, I don't know which is faster. However, I would expect that difference in performance in both of the methods you describe is imperceptible.

Upvotes: 1

Related Questions