Cost of synchronization

In a highly concurrent Java program and assuming that my methods are correctly written and correctly synchronized, I am wondering about how to determine which is better:

void synchronized something() {
     ...
}

or

void something() {
     synchronized(this) {
         ...
     }
     // here do stuff no requiring synchronization
     .
     . // do computation 'A'
     .
     synchronized(this) {
         ...
     }
     // here do other stuff no requiring synchronization
     .
     . // do computation 'B'
     .
     synchronized(this) {
         ...
     }
}

Now I realize that if computation 'A' and 'B' takes a lot of time, the second version is obviously better.

My question, however, is : at which point do you know that the second version is more efficient?

Is the second version always faster or is there an hidden cost about acquiring/releasing the lock several times?

What if my computation 'A' is simply something trivial like:

s.getString().substring( 0, 2 ).toLowerCase();
10
задан SyntaxT3rr0r 4 December 2010 в 17:10
поделиться