内存机制问题
类创建在哪儿? 对象创建在哪里?
Person类模板—>方法区
栈内存—>Person p = new Person();---->堆内存
栈内存—>创建开始, 用完立即回收 ,常见错误 StackOverflowError
方法区—>类模板 , 常量缓冲区 , 静态元素区 。方法区里面的只有一份,回收不了。
堆内存—>new创建的对象 。 Garbage Collection垃圾回收器 , GC其实是一个线程。
内存空间 | 存储的元素 | 特点 | 回收机制 |
---|---|---|---|
栈内存 | 变量空间,方法执行的临时空间 | 从创建开始,到执行完毕 | 用完立即回收 |
堆内存 | 对象空间 | 我们自己通过new申请的对象空间 ,对象空间没有任何引用即被视为垃圾 | GC垃圾回收器管理回收 |
方法区 | 常量,类模板,静态成员 | 有且仅有一份 | 不回收 |
Object类中有一个finalize(回收内存用的)方法, 如果重写也能看见对象回收。
public class Person {
//Person类默认继承Object
// hashCode equals toString getClass wait notify notifyAll clone
// finalize Object类中的一个protected方法
public Person(){
System.out.println("person对象被创建啦");
}
//重写 finalize()方法
public void finalize(){
System.out.println("person对象被回收啦");
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person();
try {
Thread.sleep(2000);//等待2秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
p = null;
//通知GC回收器去回收,但不见得立马就回收
System.gc();
}
}
GC系统提供的一个线程 , n多个回收算法(引用计数,可达性分析)。
Runtime类
Runtime类的源码中使用了饿汉式的单例模式。
Runtime类之中提供了几个管理内存的方法
maxMemory
totalMemory
freeMemory
堆内存溢出错误OutOfMemoryError
利用这三个方法我们可以查看java虚拟机给堆内存的分配的空间以及可用空间和剩余的空闲空间:
public class Test {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
long max = r.maxMemory();
long total = r.totalMemory();
long free = r.freeMemory();
System.out.println(max);//max这个数字最大,比其他两个都多一位。
System.out.println(total);
System.out.println(free);
}
}
这三个值的含义见下图:
total可用空间如果不够用,会自动扩容。
public class Test {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
long max = r.maxMemory();
long total = r.totalMemory();
long free = r.freeMemory();
System.out.println(max);//max这个数字最大,比其他两个都多一位。
System.out.println(total);
System.out.println(free);
System.out.println("------------------------------------");
Byte[] b = new Byte[(int)(max/10)];//max容量的十分之一,存入可用空间,这时候total装不下,会扩容
long max2 = r.maxMemory();
long total2 = r.totalMemory();
long free2 = r.freeMemory();
System.out.println(max2);
System.out.println(total2);
System.out.println(free2);
}
}
如果堆内存堆满了,会出现堆内存溢出错误:
java.lang.OutOfMemoryError: Java heap space
heap space指的是堆内存。