Thread Performance
The way that applications use threads and the associated costs and benefits have greatly impacted the design of many Java APIs. We will discuss some of the issues in detail in other chapters. But it is worth briefly mentioning some aspects of thread performance and how the use of threads has dictated the form and functionality of several recent Java packages.
The Cost of Synchronization
The act of acquiring locks to synchronize threads takes time, even when there is no contention. In older implementations of Java, this time could be significant. With newer VMs, it is almost negligible. However, unnecessary low-level synchronization can still slow applications by blocking threads where legitimate concurrent access otherwise could be allowed. Because of this, two important APIs, the Java Collections API and the Swing GUI API, were specifically crafted to avoid unnecessary synchronization by placing it under the developer’s control.
The java.util Collections API
replaces earlier, simple Java aggregate types—namely, Vector and Hashtable—with more fully featured and,
notably, unsynchronized types (List
and Map). The Collections API instead
defers to application code to synchronize access to collections when
necessary and provides special “fail fast” functionality to help detect
concurrent access and throw an exception. It also provides
synchronization “wrappers” that can provide safe access in the old
style. Special concurrent-access-friendly implementations of the
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access