[logback-dev] synchronization style?

Ceki Gulcu ceki at qos.ch
Thu Jul 2 09:39:29 CEST 2009


Hello,

I am hesitating between the two following styles of synchronization.

First style, with one lengthy synchronization block

synchronize(x) {
   shortOpA();
   shortOpB();
   shortOpC();
   shortOpD();
   longOp();
}

Second style, with  shorter but more numerous synchronization blocks

synchronize(a) {
   shortOpA();
}

synchronize(b) {
   shortOpB();
}

shortOpC(); // no need for synchronization
shortOpD(); // no need for synchronization

synchronize(x) {
   longOp();
}


Let us assume that longOp() takes about 5 times longer than
shortOp_N() to complete. Moreover, all operations are self contained,
with no further synchronization (locking) dependencies to external
code.

I wonder which style is better. The first style is simpler to
understand, because there is just one synchronization block. However,
the monitor is held for a longer period. In the second style, there
are more locks, so the code may be harder to follow but each lock is
held for a shorter period.

Surprisingly enough, tests (with 10 threads) show that performance is
slightly better with the first style.

Am I splitting hairs?

-- 
Ceki Gülcü
Logback: The reliable, generic, fast and flexible logging framework for Java.
http://logback.qos.ch


More information about the logback-dev mailing list