gir*_*iri 3 java synchronization
我想知道我们是否同步最终的实例变量.由于变量是最终的,因此价值不会发生变化.任何人都能解释一下吗?
Osc*_*Ryz 11
我们是否同步最终的实例变量?
是.您仍然需要同步可变对象
最终!=不可变的
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();
}
}
Run Code Online (Sandbox Code Playgroud)
后来
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();
Run Code Online (Sandbox Code Playgroud)
如果是,那么使用是什么?
您声明,在对象生命周期内无法更改给定属性.
这增加了安全性(您的对象属性不能被恶意子类替换)允许编译器优化(因为它知道将只使用引用)防止子类更改它等等.
最终和不可变的属性(如String,Integer和其他)不需要同步.
class X {
private final String name = "Oscar";
public int nameCount(){
return this.name.length(); //<-- Will return 5 ALWAYS ( actually the compiler might inline it
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4010 次 |
| 最近记录: |