[concurrency-interest] JLS 17.5

Dr Heinz M. Kabutz heinz at javaspecialists.eu
Wed Feb 26 08:58:18 EST 2020


Looking at JLS13, I noticed the following example 17.5.2:

Example 17.5-2. final Fields For Security
final fields are designed to allow for necessary security guarantees. 
Consider the

following program. 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. While the String implementation does not have 
any data races, other code could have data races involving the use of 
String objects, and the memory model makes weak guarantees for programs 
that have data races. In particular, 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". A later 
operation on the String object might see the correct offset of 4, so 
that the String object is perceived as being "/usr". Many security 
features of the Java programming language depend upon String objects 
being perceived as truly immutable, even if malicious code is using data 
races to pass String references between threads.


It assumes that String has an "offset" field and when we make a 
substring.  However, this was changed in Java 7 already, thus the JLS 
should be updated.

Regards

Heinz
-- 
Dr Heinz M. Kabutz (PhD CompSci)
Author of "The Java™ Specialists' Newsletter" - www.javaspecialists.eu
Java Champion - www.javachampions.org
JavaOne Rock Star Speaker
Tel: +30 69 75 595 262
Skype: kabutz



More information about the Concurrency-interest mailing list