Java Reference
In-Depth Information
using the low-level mechanisms provided by the platform and class library is covered in
Chapter 14 .
4.1.3. State Ownership
We implied in Section 4.1 that 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 reach-
able from a given object not part of that object's state?
When defining which variables form an object's state, we want to consider only the data that
object owns . Ownership is not embodied explicitly in the language, but is instead an ele-
ment of class design. If you allocate and populate a HashMap , you are creating multiple ob-
jects: the HashMap object, a number of Map.Entry objects used by the implementation
of HashMap , and perhaps other internal objects as well. The logical state of a HashMap in-
cludes the state of all its Map.Entry and internal objects, even though they are implemen-
ted as separate objects.
For better or worse, garbage collection lets us avoid thinking carefully about ownership.
When passing an object to a method in C++, you have to think fairly carefully about whether
you are transferring ownership, engaging in a short-term loan, or envisioning long-term joint
ownership. In Java, all these same ownership models are possible, but the garbage collector
reduces the cost of many of the common errors in reference sharing, enabling less-than-pre-
cise thinking about ownership.
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. Owner-
ship implies control, but once you publish a reference to a mutable object, you no longer have
exclusive control; at best, you might have “shared ownership”. A class usually does not own
the objects passed to its methods or constructors, unless the method is designed to explicitly
transfer ownership of objects passed in (such as the synchronized collection wrapper factory
methods).
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 col-
lection. An example is ServletContext from the servlet framework. ServletCon-
text provides a Map -like object container service to servlets where they can register and re-
trieve application objects by name with setAttribute and getAttribute . The Ser-
vletContext object implemented by the servlet container must be thread-safe, because it
Search WWH ::




Custom Search