java - why I should "final" sharing variable in multi-threading program -


my question why should use final decorate variable, list? used instance of anonymous inner class without final, won't compile.

the code looks this:

public class twothreadsonelistcurrmodi {   public static void main(string[] args)   {          final list<string> list = collections.synchronizedlist(new arraylist<string>());      (int =0 ; i<20;i++)       list.add(string.valueof(i));     thread t1 = new thread(new runnable(){        @override       public void run()       {           synchronize(list) {           system.out.println("size of list:" +list.size());           }       }     });      t1.start();     } } 

but if use normal class, fine.

public class twothreadsonelistcurrmodi2  {   public static void main(string[] args)   {          final list<string> list = collections.synchronizedlist(new arraylist<string>());     initialize list;      thread t1 = new workthread(list);     thread t2 = new workthread(list);         t1.start();       t2.start();   } } class workthread extends thread{     list<string> list;     public void run(){        sth list , synchronize block on list   }   work1(list<string> list)   {    this.list = list;  } } 

this has nothing multithreading. there because trying access list anonymous inner class' method. java sign error in case.

in case creating anonymous instance of runnable here using new keyword. trying dereference run need final.

if curious necessity of final keyword can check jon skeet's exhaustive answer explains in depth.

the point when create instance of anonymous inner class, variables used within class have values copied in via autogenerated constructor , odd if variable modified rest of method , vica versa.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -