Java中ArrayList之clear内存回收


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class TestListClear {
public static void main(String[] args) throws InterruptedException {
Runtime runtime = Runtime.getRuntime();
System.out.println("first total: " + runtime.freeMemory());
List<String> list = new ArrayList<>(100000);
System.out.println("create list total: " + runtime.freeMemory());
for (int i = 0; i < 100000; i++) {
list.add(UUID.randomUUID().toString());
}
System.out.println("add String to list total: " + runtime.freeMemory());
System.gc();
TimeUnit.SECONDS.sleep(5L);
System.out.println("first gc total: " + runtime.freeMemory());
list.clear();
// list = null;
System.gc();
TimeUnit.SECONDS.sleep(5);
System.out.println("final clear total: " + runtime.freeMemory());
}
}

1、list.clear()

可发现,clear()可以清除了对象的引用,使那些对象成为垃圾

看ArrayList的clear源码可知:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   /**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;

// 将数组元素清空设置为null,即清除了对所有元素的引用,那么系统在gc的时候会将所有的元素清除
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;

size = 0;
}

2、list = null;

可发现,赋值NULL后不仅列表中的对象变成了垃圾,为列表分配的空间也会回收

参考链接:https://blog.csdn.net/china199225/article/details/52795771

打赏
  • 版权声明: 本网站所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  1. © 2020-2021 Lauy    湘ICP备20003709号-1

请我喝杯咖啡吧~

支付宝
微信