ReentrantLock synchronizing getters and setters
-
28-02-2021 - |
Pergunta
Let's say you have the following code:
public int getSpeedX() {
speedLock.lock();
try {
return speedX;
} finally {
speedLock.unlock();
}
}
public void setSpeedX(int x) {
speedLock.lock();
try {
speedX = x;
} finally {
speedLock.unlock();
}
}
Is the return speedX OK? or should it be:
public int getSpeedX() {
int temp;
speedLock.lock();
try {
temp = speedX;
} finally {
speedLock.unlock();
}
return temp;
}
Which is correct? Or are they equivalent?
Solução
They are equivalent. Anything in a finally
block is executed, no matter how the block is exited (e.g. flow control out the bottom, return statement, or exception).
Outras dicas
java.util.concurrent.locks.ReentrantReadWriteLock
I will go for the first one which keeps the getter signature clean and tidy (no parameters).
I would put a small comment there to document the fact that the finally
block is always executed.
For the record, I actually got the exact same question from a colleague of mine once, from that point and on, I always try to comment this kind of coding to save some googling time for my code readers.