Search code examples
javajls

Clarification from Java Janguage Specification


Shouldn't it be myS.equals("/usr") in this explanation from the JLS?

Final fields are designed to allow for necessary security guarantees. Consider the following example. One thread (which we shall refer to as thread 1) executes

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

while another thread (thread 2) executes

String myS = Global.s;
if (myS.equals("/tmp"))System.out.println(myS);

String objects are intended to be immutable and string operations do not perform synchronization.


Solution

  • Actually no, that might be what you'd think at first glance, but that is intentional. Quoting further down the text (emphasis mine):

    [...] if the fields of the String class were not final, then it would be possible (although unlikely) that thread 2 could initially see the default value of 0 for the offset of the string object, allowing it to compare as equal to "/tmp"