java-为什么对象的状态可以是植根于该对象的对象图中字段的子集?

首先,我正在阅读“ Java并发实践”,它说:

An object’s state starts with its fields. If they are all of primitive type, the fields comprise the entire state.

If the object has fields that are references to other objects, its state will encompass fields from the referenced objects as well.

然后它说:

an object’s state could be a subset of the fields in the object graph rooted at that object. Why might it be a subset? Under what conditions are fields reachable from a given object not part of that object’s state?

我在书中找不到这两个问题的答案.

>为什么会是子集?
>在什么条件下,给定对象可到达的字段不属于该对象的状态?

我对以上两个引号完全感到困惑.对我来说似乎矛盾.有人可以举一个例子说明“一个对象的状态是植于该对象上的对象图中字段的子集”并回答这两个问题吗?

解决方法:

快速回答

从评论中,您的困惑似乎是:

I think the meaning is “all fields reachable from am object are part of the object’s state”. Isn’t it?

不,不是这个意思.这由作者提出的问题表达:

Under what conditions are fields reachable from a given object not part of that object’s state?

不久后回答:

Collection classes often exhibit a form of “split ownership”, in which the collection owns the state of the collection infrastructure, but client code owns the
objects stored in the collection

了解所有权

为了清楚起见,所有权确定谁可以为该状态实施同步策略.

In many cases, ownership and encapsulation go together—the object encapsulates the state it owns and owns the state it encapsulates. It is the owner of a given state variable that gets to decide on the locking protocol used to maintain the integrity of that variable’s state

封装状态后,客户端将被强制通过封装状态与状态进行交互.因此,封装者是排他性所有者,而线程安全性由排他性所有者确定.

once you publish a reference to a mutable object, you no longer have exclusive control; at best, you might have “shared ownership”.

如果对象暴露(可能是通过吸气剂),则封装器将失去专有所有权,因为客户端现在可以绕过封装器设置的任何策略.

但是,这并不能改变对象仍然由封装器部分拥有的事实-当客户端通过封装器修改对象的状态时,封装器仍可以实施其策略.

回答..

Why may it be a subset?

从书中:

If you allocate and populate a HashMap, you are creating multiple objects: the HashMap object, a number of Map.Entry objects used by the implementation of HashMap, and perhaps other internal objects as well.

HashMap可能由许多Map.Entry对象组成,形式为HashMap#Node.

由于HashMap可以控制客户端与Node的交互方式(客户端不能仅通过诸如HashMap#putVal之类的方法来确定诸如Node#hash之类的状态来创建新的Node实例),因此Node的状态被视为HashMap的子集.

回答…

Under what conditions are fields reachable from a given object not part of that object’s state?

从书中:

Collection classes often exhibit a form of “split ownership”, in which the collection owns the state of the collection infrastructure, but client code owns the
objects stored in the collection.


Servlets need not use synchronization when calling set-
Attribute and getAttribute, but they may have to use synchronization when using the objects stored in the ServletContext

集合无法控制其元素的线程安全-客户端在使用从集合接收的元素时可能必须实现自己的同步.

由于该集合无法控制其元素的线程安全性,因此它不拥有其elememts的状态.元素的状态不是集合状态的子集,只有基础结构才是.

上一篇:npm -v 报错:Error: EPERM: operation not permitted, mkdir 'C:\soft\nodejs'


下一篇:Javascript-ES6方法定义速记仅创建一个功能对象吗?