I want to access a method from within an synchronized
block. Here is an example:
public void doSomething() {
// simple stuff
// a block to reduce the synchronized code to
// what really needs to be synchronized.
synchronized(this) {
if (precondition) {
doSequentialStuff();
}
}
}
private void doSequentialStuff() {
// do stuff needs to be performed sequentially.
}
To write clean code I wondered whether it would be good to make the method doSequentialStuff
explicitly synchronized
. IMHO this would make no difference in semantic since the lock is in both cases this
and the method is guaranteed to be accessed only from the synchronized
block. I hope to increase the readability.
Any advice?
Edit: I modified the example to incorporate the comments.
If there is no legitimate code path by which doHeavyStuff
may be executed without holding the lock, then by all means make it synchronized
in order to preempt any future bugs introduced by an unwary developer. The readability of code can only improve what way.