Java final字段:是"taint"当前JLS可能的行为 [英] Java final fields: is "taint" behavior possible with the current JLS
问题描述
我目前正在尝试了解此JLS关于最终字段的部分.
为了更好地理解JLS中的文本,我还在阅读 Jeremy Manson(JMM的创建者之一)的Java内存模型.
To understand the text in the JLS better I'm also reading The Java Memory Model by Jeremy Manson (one of creators of the JMM).
本文包含的示例引起了我的兴趣:如果使具有最终字段的对象 o
对另一个线程 t
两次可见:
The paper contains the example that got me interested: if an object o
with final fields is made visible to another thread t
twice:
- 首先,不当"在
o
的构造函数完成之前接下来,适当地"使用在 o
的构造函数完成之后- first "improperly" before
o
's constructor finishes - next "properly" after
o
's constructor finishes
然后 t
可以看到半结构化的 o
,即使仅通过适当"访问也是如此.已发布的路径.
then t
can see semi-constructed o
even when it is accessed only via a "properly" published path.
这是论文的一部分:
图7.3:简单的最终语义示例
Figure 7.3: Example of Simple Final Semantics
f1是最后一个字段;其默认值为0
f1 is a final field; its default value is 0
线程1 | 线程2 | 线程3 | ||||||
---|---|---|---|---|---|---|---|---|
我们假设r1,r2和r3看不到空值.i和k可以为0或42,j必须为42. We assume r1, r2 and r3 do not see the value null. i and k can be 0 or 42, and j must be 42. 请考虑图7.3.我们不会以对最终字段多次写入的复杂性开始.目前,冻结只是在构造函数末尾发生的事情.尽管 Consider Figure 7.3. We will not start out with the complications of multiple writes to final fields; a freeze, for the moment, is simply what happens at the end of a constructor. Although ... 在线程2中读取 What about the read of 将其概念化的一种方法是,如果某个对象读取了对该对象的错误发布的引用,则认为该对象被线程污染"了.如果某个对象被线程污染,则永远不能保证该线程看到该对象的正确构造的最终字段.通常,如果线程 One way to conceptualize this is by thinking of an object being "tainted’ for a thread if that thread reads an incorrectly published reference to the object. If an object is tainted for a thread, the thread is never guaranteed to see the object’s correctly constructed final fields. More generally, if a thread 我试图在当前的JLS 任何明确允许或禁止这种行为的东西,但我发现的是: I tried to find in the current JLS anything that explicitly allows or forbids such behavior, but all I found is that:
当前的JLS是否允许这种行为? 推荐答案是的,允许这种行为. 事实证明,可以在最终字段语义的新表示/描述. Turns out that a detailed explanation of this same case is available on the personal page of William Pugh (yet another JMM author): New presentation/description of the semantics of final fields. 简短版本:
问题中的代码具有从 the code in the question has a path from
因此, As a result, 来自
... The write in Thread 1 and read in Thread 2 of 请注意,对于线程2,参考链的顺序为 Notice that for Thread 2, the deference chain orders 这篇关于Java final字段:是"taint"当前JLS可能的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆
|