注意:JEP142规范,Reduce Cache Contention on Specified Fields。
1.伪分享情况下,JDK8上,偏向于使用@Contended
伪分享的情况下,可以使用填充和JDK8的@Contended注解。
但是实验结果证明数据填充并不能做的很好,因为不同的机器、不同的操作系统对缓存行的使用情况不一样,我们很难确定我们机器上的缓存使用机制就是如我们设想的那样,所以建议使用JDK8的@Contended注解。
为什么偏向于使用@Contended注解:
- 我自己用代码试验,试验了用数据填充、用@Contended注解,从结果来看,@Contended确实可以提升几倍,比填充好。
- 另一个证据是国外的这篇博客,这篇博客解释了,为什么@Contended注解比数据填充好,原因是CPU执行instruction时,会prefetch。很多人说,填充到64bytes就可以了,但我发现这种说法的作者缺少额外的了解,我们对操作系统底层还是了解的不够。
2.@Contended注解的value
List-1 Intellij Idea中打开的Oracle JDK @Contended没有注释
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注解,源码地址
...这里有很多注释,自行查看源码...
@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。
图1 Stackoverflow上关于@Contended的value回答
3. JDK8中使用@Contended的类举例
ForkjoinPool的内部类WorkQueue
图1 JDK8中ForkjoinPool的WorkQueue
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);
}
}
}
在这里就只是举这几个例子