Search code examples
javamultithreadingconcurrencylockingreentrantlock

ReentrantLock synchronizing getters and setters


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?


Solution

  • 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).