为什么将方法参数重新分配给局部变量? [英] Why are method parameters reassigned to local variables?

查看:51
本文介绍了为什么将方法参数重新分配给局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看Java API源代码时,我经常看到方法参数已重新分配给局部变量.为什么这样做?

While looking through the Java API source code I often see method parameters reassigned to local variables. Why is this ever done?

void foo(Object bar) {
  Object baz = bar;
  //...
}

这在java.util.HashMap中

This is in java.util.HashMap

public Collection<V> values() {
  Collection<V> vs = values; 
  return (vs != null ? vs : (values = new Values())); 
}

推荐答案

这是线程安全性/更好性能的规则. HashMap 中的 values 是易失的.如果将变量分配给局部变量,它将成为局部堆栈变量,该变量自动是线程安全的.而且,修改局部堆栈变量不会强制先发生",因此在使用它时不会产生同步损失(与之不同的是,每次读/写操作都将导致易失性,这会花费您获取/释放锁的作用)

This is rule of thread safety/better performance. values in HashMap is volatile. If you are assigning variable to local variable it becomes local stack variable which is automatically thread safe. And more, modifying local stack variable doesn't force 'happens-before' so there is no synchronization penalty when using it(as opposed to volatile when each read/write will cost you acquiring/releasing a lock)

这篇关于为什么将方法参数重新分配给局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆