[logback-dev] synchronization style?
Joern Huxhorn
jhuxhorn at googlemail.com
Thu Jul 2 14:58:30 CEST 2009
Ceki Gulcu wrote:
>
> 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();
> }
>
Ideally, synchronization should be done like this, if reordering is
possible:
shortOpC();
shortOpD();
synchronize(x) {
shortOpA();
shortOpB();
longOp();
}
The longer a lock is held, the more likely starvation might occur.
I'd obviously vote for fair locking instead of synchronized since the
additional time spent obtaining the lock is much smaller than the time
blocked threads are potentially waiting to be able to work again, as
I've shown in
http://jira.qos.ch/browse/LBCLASSIC-140?focusedCommentId=11178#action_11178
>
> 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.
It's not *that* surprising for me since synchronization of any kind
includes an additional overhead incl. the decision which thread may
obtain the lock and which will have to wait some more.
>
> Am I splitting hairs?
>
Nope, a discussion like that is really necessary because this whole
issue is pretty crucial and will essentially decide how well Logback
will perform in environments with >1 CPU-cores.
This will become more and more important with more cores added in every
new CPU generation. The more cores are present, the more relevant the
issue of unfairness will become, since waiting threads will mean idling
CPUs.
Regards,
Joern.
More information about the logback-dev
mailing list