伪共享以及对应的解决办法

2020-04-21  本文已影响0人  睦月MTK

声明:关于概念相关的部分,本文不会着重讲述,请参阅列出的参考文档


一、什么是伪共享

二、一个发生了伪共享的代码示例

该段代码将会创建两个线程,两个线程将会同时操作一个对象,只不过t1线程操作对象的v1域,而t2线程操作对象的v2域,两个操作都将执行10亿次。

public class Target implements  BaseTarget{
    private volatile long v1;
    private volatile long v2;

    @Override
    public void setV1(long v1) {
        this.v1 = v1;
    }

    @Override
    public void setV2(long v2) {
        this.v2 = v2;
    }
}
public class Main {
    //...
    public static void main(String[] args) throws InterruptedException {
        falseSharingTest(false);
    }

    public static void falseSharingTest(boolean optimize){
        int times = 1000000000;
        BaseTarget target = null;
        if(optimize){
            target = new BetterTarget();
        }else{
            target = new Target();
        }
        final BaseTarget finalTarget = target;
        //我的机器是4核的所以可以这么写
        fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() - 1);
        fixedThreadPool.submit(() -> {
            for(int i =0; i < times ; i++){
                finalTarget.setV1(i);
            }
        });
        fixedThreadPool.submit(() -> {
            for(int i =0; i < times ; i++){
                finalTarget.setV2(i);
            }
        });
        long start = System.nanoTime();
        threadPoolShutdown();
        System.out.println(Duration.ofNanos(System.nanoTime() - start));
    }
    //...
}
PT4.5802031S

三、解决方案及示例
-XX:-RestrictContended
public class BetterTarget implements  BaseTarget{
    private volatile long v1;
    @Contended
    private volatile long v2;

    @Override
    public void setV1(long v1) {
        this.v1 = v1;
    }

    @Override
    public void setV2(long v2) {
        this.v2 = v2;
    }
}
public class Main {

    public static void main(String[] args) throws InterruptedException {
        falseSharingTest(true);
    }

    public static void falseSharingTest(boolean optimize) throws InterruptedException {
        //略
    }

}
PT1.0964604S

一个小小的注解使得性能足足相差了4倍!!!


参考文档:
[1] 伪共享(false sharing),并发编程无声的性能杀手

上一篇下一篇

猜你喜欢

热点阅读