java - Synchronizing var instantiation upon multiple threads -


i'm trying sync var instantiation one:

object o = new object(); string s = null;  void gets() {   if (s != null) {     return s;   }   // multiple threads stopping here   // maybe using readwritelock? write.lock?   syncronize(o) {     // if previous thread stopped sync block     // completed before, bypass     if (s != null) {       return s;     }      // no 1 before, instantiate s     s = "abc";   }   return s;  } 

is there better way handle single time instantiation of var s? maybe using locks?

declare s volatile

volatile string s; 

and we'll classic double-checked locking design pattern implementation. patterns formalized best practices dont need try , further improve code.

btw example lazy string initialization makes no sense, should expensive create object


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -