我们是否同步最终的实例变量?如果是,那么使用是什么?

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)


Ant*_*ney 5

一个重要的例外:构造对象后无法修改的final字段,一旦构造了对象,就可以通过非同步方法安全地读取

取自同步方法