java方法中把对象置null,到底能不能加速垃
1. 设定堆的大小信息,及GC打印信息
-Xms2M -Xmx3M -XX:PermSize=2M -XX:MaxPermSize=4M
-XX:+PrintGCTimeStamps -XX:-PrintClassHistogram - XX:+PrintHeapAtGC
-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
-XX:+PrintGCApplicationStoppedTime - XX:+HeapDumpOnOutOfMemoryError
2.在main方法中模拟出一个占内存很大的list对象,至少保证运行方法中单个list的大小不会挤爆内存
[java] view plain copy
public class TestGC {
public static void main(String[] args) throws InterruptedException {
List<String> list= new ArrayList<String>();
for (int i = 0; i < 100000; i++) {
String a = new String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
list.add(a);
}
}
}
- 调整堆的大小,保证运行不会报错堆栈溢出错误,接着看下面的代码
public class TestGC {
public static void main(String[] args) throws InterruptedException {
List<String> list= new ArrayList<String>();
for (int i = 0; i < 100000; i++) {
String a = new String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
list.add(a);
}
//list =null;
Thread.sleep(1000);
List<String> list2= new ArrayList<String>();
for (int i = 0; i<100000; i++) {
String a = new String("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
list2.add(a);
}
//list2 =null;
Thread.sleep(1000);
List<String> list3= new ArrayList<String>();
for (int i = 0; i < 100000; i++) {
String a = new String("cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
list3.add(a);
}
//list3 =null;
Thread.sleep(1000);
List<String> list4= new ArrayList<String>();
for (int i = 0; i<100000; i++) {
String a = new String("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");
list4.add(a);
}
//list4 =null;
Thread.sleep(1000);
List<String> list5= new ArrayList<String>();
for (int i = 0; i < 100000; i++) {
String a = new String("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
list5.add(a);
}
//list5 =null;
Thread.sleep(1000);
List<String> list6= new ArrayList<String>();
for (int i = 0; i<100000; i++) {
String a = new String("fffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
list6.add(a);
}
//list6= null;
System.out.println("运行成功。");
}
}
- 运行中内存溢出了,错误信息如下
[java] view plain copy
3. 见证奇迹的时刻到了,看看到底有木有用,把代码中的注释放开