Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification from Java Janguage Specification

Tags:

java

jls

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.

like image 986
user2757106 Avatar asked Dec 21 '22 00:12

user2757106


2 Answers

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"

like image 164
Joachim Sauer Avatar answered Jan 02 '23 01:01

Joachim Sauer


They are describing a hypothetical situation in which the returned substring might appear to be either /tmp or /usr because of a race condition. As a result it doesn't really matter which string is used for the comparison; the point of the example is that either could possibly be correct if the conditions described in this example held.

like image 35
Ernest Friedman-Hill Avatar answered Jan 02 '23 03:01

Ernest Friedman-Hill