Java Reference
In-Depth Information
9.4.1. Thread-safe Data Models
As long as responsiveness is not unduly affected by blocking, the problem of multiple threads
operating on the data can be addressed with a thread-safe data model. If the data model sup-
ports fine-grained concurrency, the event thread and background threads should be able to
share it without responsiveness problems. For example, DelegatingVehicleTracker
on page 65 uses an underlying ConcurrentHashMap whose retrieval operations offer a
high degree of concurrency. The downside is that it does not offer a consistent snapshot of
the data, which may or may not be a requirement. Thread-safe data models must also gen-
erate events when the model has been updated, so that views can be updated when the data
changes.
It may sometimes be possible to get thread safety, consistency and good responsiveness with
a versioned data model such as CopyOnWriteArrayList [CPJ 2.2.3.3]. When you ac-
quire an iterator for a copy-on-write collection, that iterator traverses the collection as it ex-
isted when the iterator was created. However, copy-on-write collections offer good perform-
ance only when traversals greatly outnumber modifications, which would probably not be the
case in, say, a vehicle tracking application. More specialized versioned data structures may
avoid this restriction, but building versioned data structures that provide both efficient con-
current access and do not retain old versions of data longer than needed is not easy, and thus
should be considered only when other approaches are not practical.
9.4.2. Split Data Models
From the perspective of the GUI, the Swing table model classes like TableModel and
TreeModel are the official repository for data to be displayed. However, these model ob-
jects are often themselves “views” of other objects managed by the application. A program
that has both a presentation-domain and an applicationdomain data model is said to have a
split-model design ( Fowler, 2005 ) .
In a split-model design, the presentation model is confined to the event thread and the other
model, the shared model , is thread-safe and may be accessed by both the event thread and
application threads. The presentation model registers listeners with the shared model so it can
be notified of updates. The presentation model can then be updated from the shared model by
embedding a snapshot of the relevant state in the update message or by having the presenta-
tion model retrieve the data directly from the shared model when it receives an update event.
The snapshot approach is simple, but has limitations. It works well when the data model is
small, updates are not too frequent, and the structure of the two models is similar. If the data
Search WWH ::




Custom Search