Question

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?

Was it helpful?

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

OTHER TIPS

They both work and are same. The first one is optimized though. Have a look at this and that should answer your question. and this link in the first link that says

copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top