ReentrantLock 同步 getter 和 setter
假设您有以下代码:
public int getSpeedX() {
speedLock.lock();
try {
return speedX;
} finally {
speedLock.unlock();
}
}
public void setSpeedX(int x) {
speedLock.lock();
try {
speedX = x;
} finally {
speedLock.unlock();
}
}
返回 speedX 可以吗?或者应该是:
public int getSpeedX() {
int temp;
speedLock.lock();
try {
temp = speedX;
} finally {
speedLock.unlock();
}
return temp;
}
哪个是正确的?或者说它们是等价的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它们是等价的。无论块如何退出(例如,从底部流出的流控制、返回语句或异常),
finally
块中的任何内容都会被执行。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).它们都工作并且相同。不过第一个已经优化了。
看看这个,它应该可以回答你的问题。第一个中的这个链接链接说
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
java.util.concurrent.locks.ReentrantReadWriteLock
http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html
java.util.concurrent.locks.ReentrantReadWriteLock
http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html
我会选择第一个,它可以保持 getter 签名干净整洁(无参数)。
我会在那里添加一个小注释来记录
finally
块始终被执行的事实。根据记录,我实际上曾经从我的一位同事那里得到过完全相同的问题,从那时起,我总是尝试评论这种编码,以节省我的代码阅读器的一些谷歌搜索时间。
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.