Java Reference
In-Depth Information
Maintaining stack confinement for object references requires a little more assistance from the
programmer to ensure that the referent does not escape. In loadTheArk , we instantiate a
TreeSet and store a reference to it in animals . At this point, there is exactly one ref-
erence to the Set , held in a local variable and therefore confined to the executing thread.
However, if we were to publish a reference to the Set (or any of its internals), the confine-
ment would be violated and the animals would escape.
Using a non-thread-safe object in a within-thread context is still thread-safe. However, be
careful: the design requirement that the object be confined to the executing thread, or the
awareness that the confined object is not thread-safe, often exists only in the head of the de-
veloper when the code is written. If the assumption of within-thread usage is not clearly doc-
umented, future maintainers might mistakenly allow the object to escape.
3.3.3. ThreadLocal
A more formal means of maintaining thread confinement is ThreadLocal , which allows
you to associate a per-thread value with a value-holding object. Thread-Local provides
Search WWH ::




Custom Search