ReentrantLock 同步 getter 和 setter

发布于 2024-12-15 08:51:52 字数 554 浏览 2 评论 0原文

假设您有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

谜泪 2024-12-22 08:51:52

它们是等价的。无论块如何退出(例如,从底部流出的流控制、返回语句或异常),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).

岁月苍老的讽刺 2024-12-22 08:51:52

它们都工作并且相同。不过第一个已经优化了。
看看这个,它应该可以回答你的问题。第一个中的这个链接链接说

复制到本地会产生最小的字节码,对于低级代码,最好编写更接近机器的代码

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

人│生佛魔见 2024-12-22 08:51:52

我会选择第一个,它可以保持 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文