user965980
user965980

Reputation: 187

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?

Upvotes: 4

Views: 1258

Answers (4)

Ravi Bhatt
Ravi Bhatt

Reputation: 3163

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

Upvotes: 1

GETah
GETah

Reputation: 21439

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.

Upvotes: 0

John Haager
John Haager

Reputation: 2115

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

Upvotes: 6

Related Questions