Class Loading vs. Object creation in Java
I am very confused over the time at which memory is allocated to Java programs. Is it "partially done" when the class is loaded ? I have read class lifecycle to be loading-> linking-> initialization->unloading. Wouldn't some memory be consumed in these processes, even though we are NOT creating object of that class ?开发者_开发技巧
I am also keen to know whether the initialization step done during classloading or object creation ?
Thanks a lot !
There are three things that need to happen before you can "use" an instance of a class, each one of which entails allocation of heap memory:
The classes bytecodes need to be loaded and linked to resolve any static dependencies on other classes.
The class needs to be initialized.
An instance of the class needs to be created.
The loading and linking of classes typically happens when you start the JVM, though it can be done "lazily" by the JVM, and it can be done dynamically; e.g. using Class.forName(...)
. This is when memory for the classes "code" is allocated.
Class initialization is normally done immediately before the first time that the class is actually used. (The precise details are set out in the JLS). This is when memory for a classes statics will be allocated.
Class creation happens when the new
construct is used. This will also trigger class initialization for a class that has not yet been initialised. This is when memory for an instance is allocated.
In addition to the above, at some point the JVM may run the JIT compiler to turn the bytecodes for a class into native code. When (and indeed if) this happens depends on the JVM version and the JVM launch options. JIT compilation will of course allocate memory to hold the classes compiled native code.
There is memory that is used by the VM and then there is memory that is used by Java objects within the VM. Class loaders as well as Class objects take up memory, but the memory for a particular instance of the class is allocated when you construct it with a "new" expression. But yes, there is some small, fixed amount of overhead memory for being able to refer to and instantiate a particular type.
I am very confused over the time at which memory is allocated to Java programs
That's because there isn't a time. Memory allocation and deallocation happens continuously throughout the life of a Java program.
Jvm will allocate memory when you do new
unless you are calling static
method in which case also it will create the class.
精彩评论