[英]How Memory Has Been Allocated Static variable and Static Block in Java?
如何在 Java 堆栈或堆中分配静态变量和静态块的内存?
class A{
static int a;
static{}
public static void main(String args[]){
A h=new A();
}
}
创建对象时如何为静态堆栈或堆分配内存。
static
关键字在java中主要用于内存管理。 我们可以将static
关键字应用于变量、方法、块和嵌套类。 static
关键字属于类而不是类的实例。
stactic
变量的内存分配仅在类加载到内存中时发生一次。
因此,一旦类加载classloader
加载了classloader
,内存将被分配给整数 a 和静态块。
静态方法(实际上是所有方法)以及静态变量都存储在堆的 PermGen 部分中。
可能比对创建它的过程的调用寿命更长的数据通常分配在堆上。 例如 new 创建可以从过程传递到过程的对象。 编译时无法确定堆的大小。 仅通过指针或引用引用,例如 C++ 中的动态对象,Java 中的所有对象
过程的本地名称在堆栈上分配空间。 编译时无法确定堆栈的大小。
有关内存管理的更多信息,请参阅以下教程: http : //www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf
在这里,您可以详细了解分步技术。
class A{
static int a; // goes to method area or Permanent-Generation (which is special mem area within Heap)
static{} // goes to method area or Permanent-Generation (which is special mem area within Heap)
public static void main(String args[]){ // goes to method area or Permanent-Generation (which is special mem area within Heap)
A h=new A(); // 1.using the "new" keyword, an object is created in
Heap
// 2. using the constructor A(), the memory has been allocated to the newly created object. This is called object instantiation, based on the variables and methods inside this A class.
//3. object ref var "h" will be created in stack
//4. using = operator, the memory address of newly created object will be assigned to the object ref h which sits inside the stack.
}
}
简而言之,静态块、类、变量、方法 - 位于堆内的永久生成区域内。
希望这能澄清大家!!! 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.