Why this extra padding of the value field in class jsr166e.Striped64.Cell?
concurrency, java, jvm
Solution
The padding is there to prevent the cache line on which the `value` field is to be shared - otherwise the value may have to re-fetched from memory just because something else on the cache line requires the whole line to be invalidated. So the goal is performance improvement.
To make things easier, Java 8 has introduced the `@Contended` annotation which does the same thing under the hood, except that it is handled by the JVM itself.
Problem
In a class introduced as part of the JSR166, the author uses so called padding to pad the single value field of the Striped64.Cell class. Here is an excerpt of that class: ``` /** * Padded variant of AtomicLong supporting only raw accesses plus CAS. The value field is placed * between pads, hoping that the JVM doesn't reorder them. * <p/> * JVM intrinsics note: It would be possible to use a release-only form of CAS here, if it were * provided. */ static final class Cell { volatile long p0, p1, p2, p3, p4, p5, p6; volatile long value; volatile long q0, q1, q2, q3, q4, q5, q6; ... ``` The author then uses CAS to modify the value atomically. In the Striped64 class, the author also uses Unsafe to access two other fields but does not apply any of such padding. My question is: Why would one need to do such a thing, introduce 14 redundant fields for padding off a single value field?