项目场景:
Java开发中使用static修饰ArrayList实例引发的问题;
工具:ideal 2018 , jdk 1.8
package com.codefish;
import java.util.ArrayList;
/**
* @author : codefish
* @description : 编程过程中, 使用static修饰集合带来的问题;
* 原因: static修饰的集合放在元空间中, 不会因为创建对象而丢失, 当第二次创建对象时, 在堆内存中开辟了一块空间存放Array()对象, 同时在栈空间压入run()方法栈帧, 在集合中加入1, 输出;
* Java中元空间共享, 且static修饰的集合与对象的创建无关, 只在类加载的时候创建一次, 所 有这些循环调用, 其实访问的都是同一个集合;
* @Date : 15:15 2021/8/27
* @return:
*/
public class TestStatic {
public static void main(String[] args) {
int i = 10;
while (i > 0){
Array array = new Array();
System.out.println(array.run());
i --;
}
}
}
// OutPut:
//[1]
//[1, 1]
//[1, 1, 1]
//[1, 1, 1, 1]
//[1, 1, 1, 1, 1]
//[1, 1, 1, 1, 1, 1]
//[1, 1, 1, 1, 1, 1, 1]
//[1, 1, 1, 1, 1, 1, 1, 1]
//[1, 1, 1, 1, 1, 1, 1, 1, 1]
//[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
class Array {
private static ArrayList arrayList = new ArrayList();
public ArrayList run(){
arrayList.add(1);
return arrayList;
}
}
原因分析:
static修饰的集合放在元空间中, 不会因为创建对象而丢失, 当第二次创建对象时, 在堆内存中开辟了一块空间存放Array()对象, 同时在栈空间压入run()方法栈帧, 在集合中加入1, 输出;
* Java中元空间共享, 且static修饰的集合与对象的创建无关, 只在类加载的时候创建一次, 所 有这些循环调用, 其实访问的都是同一个集合
内存图(大概):