博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java内存模型FAQ(八)Final字段如何改变它们的值
阅读量:6875 次
发布时间:2019-06-26

本文共 1791 字,大约阅读时间需要 5 分钟。

原文: 第八章

译者:Alex

我们可以通过分析String类的实现具体细节来展示一个final变量是如何可以改变的。

String对象包含了三个字段:一个character数组,一个数组的offset和一个length。实现String类的基本原理为:它不仅仅拥有character数组,而且为了避免多余的对象分配和拷贝,多个String和StringBuffer对象都会共享相同的character数组。因此,String.substring()方法能够通过改变length和offset,而共享原始的character数组来创建一个新的String。对一个String来说,这些字段都是final型的字段。

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

字符串s2的offset的值为4,length的值为4。但是,在旧的内存模型下,对其他线程来说,看到offset拥有默认的值0是可能的,而且,稍后一点时间会看到正确的值4,好像字符串的值从“/usr”变成了“/tmp”一样。

旧的Java内存模型允许这些行为,部分JVM已经展现出这样的行为了。在新的Java内存模型里面,这些是非法的。

原文

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.

A 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.

转载地址:http://gnmfl.baihongyu.com/

你可能感兴趣的文章
Retrofit与Rxjava封装终结者(一)基本用法
查看>>
Weex 在饿了么前端的实践
查看>>
Element源码分析系列3-Button(按钮)
查看>>
ES6零基础教学_解析彩票项目-学习笔记(三)
查看>>
Django2 web实战01-启动项目
查看>>
玩转iOS开发:4.《Core Animation》CALayer的视觉效果
查看>>
Flutter「发布预览版 2」让 iOS 应用至臻完美
查看>>
隐式动画的性能瓶颈
查看>>
30 天精通 RxJS(24): Observable operators - multicast, refCount, publish, share
查看>>
js选择排序
查看>>
SpringBoot详解(四)-优雅地处理日志
查看>>
Glide 知识梳理(4) 自定义animate
查看>>
Android 注解系列之Annotation(二)
查看>>
JavaEE进阶知识学习-----SpringCloud(五)Eureka和Zookeeper区别
查看>>
Function构造函数、 函数声明 、 函数表达式 的区别
查看>>
类似if一样的自定义代码块
查看>>
[译]如何在 iOS 上实现类似 Airbnb 中的可展开式菜单
查看>>
极光推送集成Module中遇到的坑
查看>>
读书笔记 Effective Objective C 2 0 (未完待续)
查看>>
利用transform实现表头固定
查看>>