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
Post a Comment