Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a compiler assign a value to a variable even before the variable is actually initiated?

I've just read http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=5 and it says:

the compiler is free to assign a value to the singleton member variable before the singleton's constructor is called

I'm wondering if it is a typo. Do they actually really wanted to say: the implementation of the JVM is free to instead of the compiler is free to.

and my second question is that do we have this issue with C#/VB as well? (in which the ""compiler"" is free to assign a value to a variable even before the variable is fully initiated/even before the constructor function of the class of the variable is fully ran.

like image 780
Pacerier Avatar asked Sep 11 '25 07:09

Pacerier


1 Answers

In Java, allocating the memory for an object and calling the constructor are two separate operations. For example, something like

Object o = new Object();

compiles into these bytecodes:

0:  new #2; //class java/lang/Object
3:  dup
4:  invokespecial   #1; //Method java/lang/Object."<init>":()V
7:  astore_1

After instruction 0, a reference to an allocated but unconstructed object is on the stack. The constructor isn't called until offset 4. There is definitely nothing keeping the compiler from assigning that reference to any variable it wants to, including a static member. The article is therefore correct.

I don't know CLR bytecode, but I imagine it cleaves rather closely to the JVM's instruction set, and I'd guess the same sort of thread-related caveat would exist for that runtime as well. It certainly holds for native code compilers.

like image 65
Ernest Friedman-Hill Avatar answered Sep 12 '25 20:09

Ernest Friedman-Hill