Java Reference
In-Depth Information
complex CPUs with more caching and registers are also becoming more commonplace,
which will expose hidden performance issues like this.
QUICK SUMMARY
1. Thread synchronization has two performance costs: it limits the scalability of an
application, and there is a cost in obtaining locks.
2. The memory semantics of synchronization, CAS-based utilities, and the volat-
ile keyword can have a large performance impact, particularly on large machines
with many registers.
Avoiding Synchronization
If synchronization can be avoided altogether, then locking penalties will not affect the applic-
ation's performance. There are two general approaches to achieve that.
The first approach is to use different objects in each thread so that access to the objects will
be uncontended. Many Java objects are synchronized to make them thread-safe but don't ne-
cessarily need to be shared. The Random class falls into that category; Chapter 12 shows an
example within the JDK where the thread-local technique was used to develop a new class to
avoid the synchronization in that class.
On the flip side, many Java objects are expensive to create or use a substantial amount of
memory. Take, for example, the NumberFormat class: instances of that class are not thread-
safe, and the internationalization required to create an instance makes constructing new ob-
jects quite expensive. A program could get by with a single, shared global NumberFormat in-
stance, but access to that shared object would need to be synchronized.
Instead, a better pattern is to use a ThreadLocal object:
public
public class
class Thermometer
Thermometer {
private
private static
static ThreadLocal < NumberFormat > nfLocal = new
new ThreadLocal <>() {
public
public NumberFormat initialValue () {
NumberFormat nf = NumberFormat . getInstance ();
nf . setMinumumIntegerDigits ( 2 );
return
return nf ;
}
}
Search WWH ::




Custom Search