当返回值不重要时,当返回值被忽略时,AtomicInteger.getAndIncrement()和AtomicInteger.incrementAndGet()方法之间有什么区别(甚至在实践中是不相关的)吗?
我正在考虑哪些差异会更惯用,以及哪些会在同步的CPU缓存中放入较少的负载,或者其他任何实际上可以帮助决定使用哪个缓存比抛硬币更合理的任何东西。
发布于 2013-03-01 17:29:22
由于没有给出实际问题的答案,基于其他答案(谢谢,支持)和Java约定,以下是我的个人意见:
incrementAndGet()更好,因为方法名称应该以描述操作的动词开头,并且此处的预期操作仅用于递增。
以动词开头是常见的Java约定,官方文档也对此进行了描述:
"Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized."
发布于 2013-02-28 21:58:11
代码本质上是相同的,所以无关紧要:
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}发布于 2013-02-28 21:58:21
不,没有区别(如果你不关心返回值)。
这些方法(在OpenJDK中)的代码不同之处只在于一个使用return next,另一个使用return current。
两者都在幕后使用compareAndSet,并使用完全相同的算法。两者都需要知道旧值和新值。
https://stackoverflow.com/questions/15137308
复制相似问题