Java Reference
In-Depth Information
model is large or updates are very frequent, or if one or both sides of the split contain in-
formation that is not visible to the other side, it can be more efficient to send incremental
updates instead of entire snapshots. This approach has the effect of serializing updates on the
shared model and recreating them in the event thread against the presentation model. Another
advantage of incremental updates is that finer-grained information about what changed can
improve the perceived quality of the display—if only one vehicle moves, we don't have to
repaint the entire display, just the affected regions.
Consider a split-model design when a data model must be shared by more than one thread
and implementing a thread-safe data model would be inadvisable because of blocking, con-
sistency, or complexity reasons.
9.5. Other Forms of Single-threaded Subsystems
Thread confinement is not restricted to GUIs: it can be used whenever a facility is implemen-
ted as a single-threaded subsystem. Sometimes thread confinement is forced on the developer
for reasons that have nothing to do with avoiding synchronization or deadlock. For example,
some native libraries require that all access to the library, even loading the library with Sys-
tem.loadLibrary , bemade from the same thread.
Borrowing from the approach taken by GUI frameworks, you can easily create a dedicated
thread or single-threaded executor for accessing the native library, and provide a proxy object
that intercepts calls to the thread-confined object and submits them as tasks to the dedicated
thread. Future and newSingleThreadExecutor work together to make this easy; the
proxy method can submit the task and immediately call Future.get to wait for the res-
ult. (If the class to be threadconfined implements an interface, you can automate the process
of having each method submit a Callable to a background thread executor and waiting for
the result using dynamic proxies.)
Summary
GUI frameworks are nearly always implemented as single-threaded subsystems in which all
presentation-related code runs as tasks in an event thread. Because there is only a single
event thread, long-running tasks can compromise responsiveness and so should be executed
in background threads. Helper classes like SwingWorker or the BackgroundTask class
built here, which provide support for cancellation, progress indication, and completion indic-
ation, can simplify the development of long-running tasks that have both GUI and non-GUI
components.
Search WWH ::




Custom Search