性能优化-volatile修饰数组和对象

无他,我也想知道答案。翻尽百度和谷歌前十页,无定论。

工具

hsdis-amd64.dylib
jitwatch
参考Mac下hsdis和jitwatch下载和使用

测试方式

  • 判断依据
    volatile指令生成的汇编会带有lock前缀

  • 测试代码

public class Teacher {
    public volatile int[] student = new int[]{1,2,3};
    public int add(int a, int b) {
        int temp = a + b;
        //重新赋值student[0]
        student[0]+=temp;
        temp +=1;

        return temp;
    }

    public int add2(int a, int b) {
        int temp = a + b;
        temp +=1;
        //重新赋值student数组
        student=new int[]{1,2,3};
        return temp;
    }

    public static void main(String[] args) {
        Teacher test = new Teacher();

        int sum = 0;

        for (int i = 0; i < 1000000; i++) {
            sum = test.add(sum, 1);
        }
        System.out.println("Sum:" + sum);
        System.out.println("Test.sum:" + test.student[0]);

        for (int i = 0; i < 1000000; i++) {
            sum = test.add2(sum, 1);
        }
        System.out.println("Sum:" + sum);
        System.out.println("Test.sum:" + test.student[0]);
    }
}
  • jvm参数配置

-XX:+UnlockDiagnosticVMOptions
-XX:+TraceClassLoading
-XX:+PrintAssembly
-XX:+LogCompilation
-XX:LogFile=live.log
  • jitwatch配置

    注意配置选择包路径和class文件夹路径,选择类会有问题

  • jitwatch分析
    对数组元素赋值

    对数组赋值

结论

volatile修饰数组,仅保证对数组本身操作的可见性和指令重排,不保证数组内部元素。用同样的方法分析对象,也仅保证对象本身,不保证对象内部的属性。

转载请注明:这不是一只猫的博客 » 点击阅读原文

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦