我们是否同步最终的实例变量?如果是,那有什么用?
我想知道我们是否同步最终的实例变量.由于变量是最终的,因此值不能更改.谁能解释一下?
解决方案我们会同步最终的实例变量吗?
是的.您仍然需要同步可变对象
最终 != 不可变
公共类的东西 {私有最终列表列表 = new ArrayList();公共无效添加(字符串值){this.list.add(value);}公共整数计数(){返回 this.list.size();}}
稍后
Something s = new Something();线程 a = new Thread() {公共无效运行(){s.add("s");s.add("s");s.add("s");}};线程 b = 新线程(){公共无效运行(){s.count();s.count();}};a.start();b.开始();
<块引用>
如果是,那有什么用?
您声明,在对象生命周期内不能更改给定属性.
这增加了安全性(您的对象属性不能被恶意子类替换)允许编译器优化(因为它知道永远只会使用一个引用)防止子类改变它等等.
既是最终的又是不可变的属性(如字符串、整数等)不需要同步.
class X {私人最终字符串名称=奥斯卡";公共 int nameCount(){返回 this.name.length();//<-- 总是返回 5 (实际上编译器可能内联它}}
I like to know do we synchronize the instance variable which are final. As variables are final there can not be change in the value. Can anybody explain this?
解决方案Do we synchronize instance variables which are final?
Yes. You still have to synchronize mutable objects
final != immutable
public class Something {
private final List list = new ArrayList();
public void add( String value ) {
this.list.add( value );
}
public int count() {
return this.list.size();
}
}
Later
Something s = new Something();
Thread a = new Thread() {
public void run(){
s.add( "s" );
s.add( "s" );
s.add( "s" );
}
};
Thread b = new Thread(){
public void run() {
s.count();
s.count();
}
};
a.start();
b.start();
If yes then whats the use?
You're declaring, that a given attribute can't be changed during the object life time.
This increases the security ( your object attribute can't be replaced by a malicious subclass ) Allows compiler optimizations ( because it knows that only a reference will be used ever ) Prevents subclasses from changing it and so on.
An attribute that is both, final and immutable ( like String, Integer and others ) doesn't need synchronization.
class X {
private final String name = "Oscar";
public int nameCount(){
return this.name.length(); //<-- Will return 5 ALWAYS ( actually the compiler might inline it
}
}
相关文章