Java Reference
In-Depth Information
an unmodifiable but “live” view of the vehicle locations. This means that if thread A calls
getLocations and thread B later modifies the location of some of the points, those
changes are reflected in the Map returned to thread A . As we remarked earlier, this can be
a benefit (more up-to-date data) or a liability (potentially inconsistent view of the fleet), de-
pending on your requirements.
If an unchanging view of the fleet is required, getLocations could instead return a shal-
low copy of the locations map. Since the contents of the Map are immutable, only the
structure of the Map , not the contents, must be copied, as shown in Listing 4.8 (which returns
a plain HashMap , since getLocations did not promise to return a thread-safe Map ).
Listing 4.8. Returning a Static Copy of the Location Set Instead of a “Live” One.
4.3.2. Independent State Variables
The delegation examples so far delegate to a single, thread-safe state variable. We can also
delegate thread safety to more than one underlying state variable as long as those underlying
state variables are independent , meaning that the composite class does not impose any invari-
ants involving the multiple state variables.
VisualComponent in Listing 4.9 is a graphical component that allows clients to register
listeners for mouse and keystroke events. It maintains a list of registered listeners of each
type, so that when an event occurs the appropriate listeners can be invoked. But there is no
relationship between the set of mouse listeners and key listeners; the two are independent,
and therefore VisualComponent can delegate its thread safety obligations to two under-
lying thread-safe lists.
Listing 4.9. Delegating Thread Safety to Multiple Underlying State Variables.
Search WWH ::




Custom Search