4

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?

Ravi Bhatt
  • 3,147
  • 19
  • 21
user965980
  • 187
  • 7

4 Answers4

6

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

John Haager
  • 2,107
  • 1
  • 17
  • 22
  • 1
    Not quite true; from what I understand, if you put a `System.exit(int exitcode)` in a try, the finally won't be executed... – BenCole Nov 16 '11 at 20:57
  • I would imagine that System.exit is a special case since it wants to immediately halt the JVM. – John Haager Nov 16 '11 at 21:58
1

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

Community
  • 1
  • 1
Ravi Bhatt
  • 3,147
  • 19
  • 21
0

java.util.concurrent.locks.ReentrantReadWriteLock

http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html

Vladislav Bauer
  • 952
  • 8
  • 19
0

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.

GETah
  • 20,922
  • 7
  • 61
  • 103