原文: 第八章




String s1 = "/usr/tmp";
String s2 = s1.substring(4); 




How can final fields appear to change their values?

One of the best examples of how final fields’ values can be seen to change involves one particular implementation of the String class.

String can be implemented as an object with three fields — a character array, an offset into that array, and a length. The rationale for implementing String this way, instead of having only the character array, is that it lets multiple String and StringBufferobjects share the same character array and avoid additional object allocation and copying. So, for example, the method String.substring() can be implemented by creating a new string which shares the same character array with the original String and merely differs in the length and offset fields. For a String, these fields are all final fields.

String s1 = "/usr/tmp";
String s2 = s1.substring(4); 

The string s2 will have an offset of 4 and a length of 4. But, under the old model, it was possible for another thread to see the offset as having the default value of 0, and then later see the correct value of 4, it will appear as if the string “/usr” changes to “/tmp”.

The original Java Memory Model allowed this behavior; several JVMs have exhibited this behavior. The new Java Memory Model makes this illegal.

原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: Java内存模型FAQ(八)Final字段如何改变它们的值

  • Trackback 关闭
  • 评论 (1)
    • 浪子心声
    • 2014/05/01 8:27下午

    感觉这句翻译的不是很准确: String.substring()方法能够通过改变length和offset,而共享原始的character数组来创建一个新的String。

    我觉得原文的意思是:我们可以通过共享原始的character数组,仅仅改变length和offset来实现String.substring() 方法。

return top