Java Reference
In-Depth Information
3.2. Publication and Escape
Publishing
an object means making it available to code outside of its current scope, such as
by storing a reference to it where other code can find it, returning it from a nonprivate meth-
od, or passing it to a method in another class. In many situations, we want to ensure that ob-
jects and their internals are
not
published. In other situations, we do want to publish an object
for general use, but doing so in a thread-safe manner may require synchronization. Publishing
internal state variables can compromise encapsulation and make it more difficult to preserve
invariants; publishing objects before they are fully constructed can compromise thread safety.
An object that is published when it should not have been is said to have
escaped
.
Section 3.5
covers idioms for safe publication; right now, we look at how an object can escape.
The most blatant form of publication is to store a reference in a public static field, where any
HashSet
and publishes it by storing a reference to it into
knownSecrets
.
Listing 3.5. Publishing an Object.
Publishing one object may indirectly publish others. If you add a
Secret
to the published
knownSecrets
set, you've also published that
Secret
, because any code can iterate the
Set
and obtain a reference to the new
Secret
. Similarly, returning a reference from a
lishes the supposedly private array of state abbreviations.
Listing 3.6. Allowing Internal Mutable State to Escape.
Don't do this.