Java Reference
In-Depth Information
Publishing states in this way is problematic because any caller can modify its contents. In
this case, the states array has escaped its intended scope, because what was supposed to
be private state has been effectively made public.
Publishing an object also publishes any objects referred to by its nonprivate fields. More
generally, any object that is reachable from a published object by following some chain of
nonprivate field references and method calls has also been published.
From the perspective of a class C , an alien method is one whose behavior is not fully spe-
cified by C . This includes methods in other classes as well as overrideable methods (neither
private nor final ) in C itself. Passing an object to an alien method must also be con-
sidered publishing that object. Since you can't know what code will actually be invoked, you
don't know that the alien method won't publish the object or retain a reference to it that might
later be used from another thread.
Whether another thread actually does something with a published reference doesn't really
matter, because the risk of misuse is still present. [7] Once an object escapes, you have to as-
sume that another class or thread may, maliciously or carelessly, misuse it. This is a compel-
ling reason to use encapsulation: it makes it practical to analyze programs for correctness and
harder to violate design constraints accidentally.
A final mechanism by which an object or its internal state can be published is to publish an
inner class instance, as shown in ThisEscape in Listing 3.7 . When ThisEscape pub-
lishes the EventListener , it implicitly publishes the enclosing ThisEscape instance
as well, because inner class instances contain a hidden reference to the enclosing instance.
Listing 3.7. Implicitly Allowing the this Reference to Escape. Don't do this.
Search WWH ::




Custom Search