Thursday February 08, 2007
Joseph D. Darcy's Sun WeblogJoseph D. Darcy's Sun Weblog Boxing and Caches: Integer.valueOf(int) and friends
Recently, various folks have been
discussing some code I wrote for the wrapper classes,
As correctly inferred, this caching code was added to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive), as required by the language specification. Since the same object must be returned for integral values in this range, once the autoboxed value for, say, 0 is created, it must be retained until the virtual machine exits. That leaves the issue of whether or not the values in question are created eagerly or lazily and whether or not any container for those values is created eagerly or lazily.
The code above lazily creates the container object, but eagerly
populates the object when it is created. This avoids having to use
any synchronization when the elements are accessed. Of the three
practical potential lazy-eager combinations, initially I planned to use the dual
approach, eagerly creating an
One reason I used the literal values "-128" and "127" in the code above is that those are the numbers given the specification and it is clear what they mean when used in the comparisons. Another code reviewer offered
paired with
and
Benchmarking this kind of caching code is difficult because what
combination of lazy and eager allocation works best will be very
dependent on the imposed workload. Therefore, something that always
performs reasonably well is in some sense more robust than an
algorithm that is really fast is some circumstances but much slower in
others. In any case, I second the recommendation to use
|
Calendar
RSS Feeds
All /Annotation Processing /General /Java /JavaOne /Numerics /OpenJDK SearchLinks
NavigationReferersToday's Page Hits: 109 |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||