ReentrantLock Syncs Recipients and Setters

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 rate X OK? or should be:

 public int getSpeedX() { int temp; speedLock.lock(); try { temp = speedX; } finally { speedLock.unlock(); } return temp; } 

What is right? Or are they equivalent?

+4
source share
4 answers

They are equivalent. Anything in the finally block is executed regardless of how the block exits (for example, flow control from the bottom, return statement, or exception).

+5
source

Both of them work and are the same. However, the first is optimized. Take a look at this and this should answer your question. and the link in the first link that says

copying to local machines creates the smallest bytecode, and for low-level code it's nice to write code that is a little closer to the machine

+1
source

I will go for the first one that keeps the recipient's signature clean and neat (no parameters). I would put a little comment there to capture the fact that the finally block is always executed. For the record, I actually had the same question from my colleague, from now on and on, I always try to comment on this type of coding in order to save time reading code for my code readers.

0
source

Source: https://habr.com/ru/post/1381207/


All Articles