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();
}
}
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 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 ?
Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem.
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.
Volatile fields are instance or class (static) variables and are stored in the heap.
By declaring the counter variable volatile all writes to the counter variable will be written back to main memory immediately. Also, all reads of the counter variable will be read directly from main memory. Declaring a variable volatile thus guarantees the visibility for other threads of writes to that variable.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With