gpt4 book ai didi

java - 如何使用 long 而不是 int 可以防止以下方法 - Effective Java

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:42:51 26 4
gpt4 key购买 nike

考虑以下摘自 Joshua Bloch - Effective Java,第 263 页的代码

// Broken - requires synchronization!
private static volatile int nextSerialNumber = 0;
public static int generateSerialNumber() {
return nextSerialNumber++;
}

One way to fix the generateSerialNumber method is to add the synchronized modifier to its declaration. This ensures that multiple invocations won’t be interleaved, and that each invocation will see the effects of all previous invocations. Once you’ve done that, you can and should remove the volatile modifier from nextSerialNumber. To bulletproof the method, use long instead of int, or throw an exception if nextSerialNumber is about to wrap.

  1. 我知道我们可以在使 generateSerialNumber 同步 之后删除 volatile,因为它是多余的。但是,它有什么害处吗? 如果我同时拥有同步和 volatile 的任何性能损失

private static volatile int nextSerialNumber = 0;
public static synchronized int generateSerialNumber() {
return nextSerialNumber++;
}

  1. 使用 long 而不是 int 是什么意思? 我不明白这个防弹的方法是怎样的?

最佳答案

这只是意味着 long 比 int 能容纳更多的数字。

or throw an exception if nextSerialNumber is about to wrap

暗示这里的问题是你用完了数字,你最终会溢出。您要确保不会发生这种情况。问题是,如果您处于可能的最大整数并且递增,则程序不会失败。它很高兴没有递增,但结果不再正确。

使用 long 将推迟这种可能性。抛出异常将表明它已经发生。

关于java - 如何使用 long 而不是 int 可以防止以下方法 - Effective Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4736018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com