java - why the following program can work under JLS spec on JVM memory model -



java - why the following program can work under JLS spec on JVM memory model -

on jls 3, 17.5 final field semantics's sec give-and-take part: http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.5

it said mys can equals "/tmp", can not understand this. 1 can give more explain? point illustration tells, mean if want share global.s between multi thread, need create final(if final, can not alter after construction) or need sync when read , write? or declare string array length 1 , final can changed , shared??

the original contents in jls:

consider next example. 1 thread (which shall refer thread 1) executes

global.s = "/tmp/usr".substring(4);

while thread (thread 2) executes

string mys = global.s; if (mys.equals("/tmp"))system.out.println(mys);

the explain in jls:

string objects intended immutable , string operations not perform synchronization. while string implementation not have info races, other code have info races involving utilize of strings, , memory model makes weak guarantees programs have info races. in particular, if fields of string class not final, possible (although unlikely) thread 2 see default value of 0 offset of string object, allowing compare equal "/tmp". later operation on string object might see right offset of 4, string object perceived beingness "/usr". many security features of java programming language depend upon strings beingness perceived immutable, if malicious code using info races pass string references between threads.

strings implemented using char[], offset, , count. substring method constructs new string object same char[] , new offset , count. based on execution semantics, possible new string partially initialized when thread 2 attempts access it. according the source, substring returns new string object constructed simple constructor:

644 // bundle private constructor shares value array speed. 645 string(int offset, int count, char value[]) { 646 this.value = value; 647 this.offset = offset; 648 this.count = count; 649 }

so without marking char[], offset, , count final in string class definition, thread 2 might see inconsistent values when accesses them. if happens, char[] set, offset , count might wrong. if offset still showing default of 0, you'd see whole string. of course, require amazing timing, specific reordering of instructions jit, , whole host of "luck" create happen.

java jvm

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -