How to decompile mutable variable in Java?

I was told that the volatile keyword can add a memory barrier before writing a variable operation. Therefore, I am writing 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(); } } 

And then decompile it:

 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 } 

I don’t see anything related to the memory barrier, and then I remove volatile and decompile it again, the bytecode does not change at all.

How can I find anything in bytecode?

+6
source share
3 answers

The concept of a memory barrier does not exist at the Java specification level. This is a low-level implementation detail for some processor architectures, such as the NUMA architecture, which is most popular today.

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

+9
source

If you check it with javap and the correct parameters, the ACC_VOLATILE flag will appear:

 javap -v -p Test 

Print

  private static volatile Test t; flags: ACC_PRIVATE, ACC_STATIC, ACC_VOLATILE 

(flags are defined in the jvm specification Chapter 4. Class file format )

+6
source

Adding volatile to a field does not change the Java bytecode that reads or writes this field. It only changes the interpretation of the program using the JVM or JIT compilation. It also affects optimization.

Field flags

Read and write synchronization

+1
source

Source: https://habr.com/ru/post/946413/


All Articles