Java Reference
In-Depth Information
There are advantages to using a private lock object instead of an object's intrinsic lock (or any
other publicly accessible lock). Making the lock object private encapsulates the lock so that
client code cannot acquire it, whereas a publicly accessible lock allows client code to parti-
cipate in its synchronization policy—correctly or incorrectly. Clients that improperly acquire
another object's lock could cause liveness problems, and verifying that a publicly accessible
lock is properly used requires examining the entire program rather than a single class.
4.2.2. Example: Tracking Fleet Vehicles
Counter in Listing 4.1 is a concise, but trivial, example of the Java monitor pattern. Let's
build a slightly less trivial example: a “vehicle tracker” for dispatching fleet vehicles such as
taxicabs, police cars, or delivery trucks. We'll build it first using the monitor pattern, and then
see how to relax some of the encapsulation requirements while retaining thread safety.
Each vehicle is identified by a String and has a location represented by ( x , y ) coordinates.
The VehicleTracker classes encapsulate the identity and locations of the known
vehicles, making them well-suited as a data model in a modelview-controller GUI application
where it might be shared by a view thread and multiple updater threads. The view thread
would fetch the names and locations of the vehicles and render them on a display:
Search WWH ::




Custom Search