注意:JEP142规范,Reduce Cache Contention on Specified Fields。java
伪分享的状况下,可使用填充和JDK8的@Contended注解。缓存
可是实验结果证实数据填充并不能作的很好,由于不一样的机器、不一样的操做系统对缓存行的使用状况不同,咱们很难肯定咱们机器上的缓存使用机制就是如咱们设想的那样,因此建议使用JDK8的@Contended注解。dom
为何偏向于使用@Contended注解:jvm
List-1 Intellij Idea中打开的Oracle JDK @Contended没有注释ide
package sun.misc; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface Contended { String value() default ""; }
List-2 来看openJDK的@Contended注解,源码地址fetch
...这里有不少注释,自行查看源码... @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface Contended { /** * The (optional) contention group tag. * This tag is only meaningful for field level annotations. * * @return contention group tag. */ String value() default ""; }
openJDK的Contended.java中有详细的注释,这个value只有在类属性上才有意义,表示"contention group tag",理解字面意思,可是没有理解具体含义。查google,查到Stackoverflow上别人的回复,说的和List-2注释差很少,理解字面意思,可是没理解含义,原文地址。我把别人的回答截图,以下图1。ui
图1 Stackoverflow上关于@Contended的value回答this
ForkjoinPool的内部类WorkQueuegoogle
图1 JDK8中ForkjoinPool的WorkQueuespa
List-3 JDK8中Thread内部属性,这几个属性与ThreadLocalRandom有关
// The following three initially uninitialized fields are exclusively // managed by class java.util.concurrent.ThreadLocalRandom. These // fields are used to build the high-performance PRNGs in the // concurrent code, and we can not risk accidental false sharing. // Hence, the fields are isolated with @Contended. /** The current seed for a ThreadLocalRandom */ @sun.misc.Contended("tlr") long threadLocalRandomSeed; /** Probe hash value; nonzero if threadLocalRandomSeed initialized */ @sun.misc.Contended("tlr") int threadLocalRandomProbe; /** Secondary seed isolated from public ThreadLocalRandom sequence */ @sun.misc.Contended("tlr") int threadLocalRandomSecondarySeed;
List-4 JDK8中Striped64的内部类Cell
/** * Padded variant of AtomicLong supporting only raw accesses plus CAS. * * JVM intrinsics note: It would be possible to use a release-only * form of CAS here, if it were provided. */ @sun.misc.Contended static final class Cell { volatile long value; Cell(long x) { value = x; } final boolean cas(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long valueOffset; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> ak = Cell.class; valueOffset = UNSAFE.objectFieldOffset (ak.getDeclaredField("value")); } catch (Exception e) { throw new Error(e); } } }
在这里就只是举这几个例子