Do we synchronize instance variables which are final? If yes then whats the use?(我们是否同步最终的实例变量?如果是,那有什么用?)
问题描述
我想知道我们是否同步最终的实例变量.由于变量是最终的,因此值不能更改.谁能解释一下?
我们会同步最终的实例变量吗?
是的.您仍然需要同步可变对象
最终 != 不可变
公共类的东西 {私有最终列表列表 = 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
}
}
这篇关于我们是否同步最终的实例变量?如果是,那有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我们是否同步最终的实例变量?如果是,那有什么用?


基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01