如何在 Java 中反编译 volatile 变量? [英] How to decompile volatile variable in Java?

查看:31
本文介绍了如何在 Java 中反编译 volatile 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被告知 volatile 关键字可以在变量的写操作之前添加内存屏障.所以我写了代码:

I have been told that the volatile keyword could add memory barrier before write operation of the variable. So i write the code:

public class Test {
    private Object o;

    public Test() {
        this.o = new Object();
    }

    private volatile static Test t;

    public static void createInstance() {
        t = new Test();             // volatile would insert memory barrier here.
    }

    public static void main(String[] args) throws Exception {
        Test.createInstance();
    }
}

然后反编译:

Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   aload_0
   5:   new #2; //class java/lang/Object
   8:   dup
   9:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   12:  putfield    #3; //Field o:Ljava/lang/Object;
   15:  return

public static void createInstance();
  Code:
   0:   new #4; //class Test
   3:   dup
   4:   invokespecial   #5; //Method "<init>":()V
   7:   putstatic   #6; //Field t:LTest;
   10:  return

public static void main(java.lang.String[])   throws java.lang.Exception;
  Code:
   0:   invokestatic    #7; //Method createInstance:()V
   3:   return

}

我看不到任何与内存屏障相关的内容,然后我删除了volatile并再次反编译,字节码根本没有改变.

I can't see anything related to memory barrier, and then i remove the volatile and decompile it again, the byte code doesn't change at all.

我怎么能在字节码中找到任何东西?

How could i find anything in byte code ?

推荐答案

内存屏障的概念在 Java 规范级别不存在.它是某些 CPU 架构的低级实现细节,例如当今最流行的 NUMA 架构.

The concept of memory barrier doesn't exist at the level of Java specification. It is a low-level implementation detail of certain CPU architectures, such as the NUMA architecture which is the most popular today.

因此,您需要查看特定 JVM 实现中的即时编译器生成的机器代码,例如 x86 架构上的 HotSpot.在那里,如果你足够熟练地解释 x86 机器码,你就会看到内存屏障的表现.

Therefore you would need to look at the machine code produced by a Just-in-Time compiler inside a specific JVM implementation, such as HotSpot on an x86 architecture. There, if you are skilled enough to interpret x86 machine code, you would see the manifestation of the memory barrier.

这篇关于如何在 Java 中反编译 volatile 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆