[英]Why does it seem like my Java process consumes more memory with time? Am I generating a memory leak?
我有一个Java RESTful服务,该服务每10秒创建一个新的JSON对象,并将其推送到AngularJS使用的URL。
问题是我认为旧的JSON对象没有在内存中释放。 当我运行任务管理器时,我看到java
进程的大小大约每10秒增加一次。 我不希望这种情况在无限期运行时发生。
我怎样才能解决这个问题?
这是课程:
@Path("/")
public class MQDepthJson extends TimerTask {
public MQDepthJson() {
}
private int count = 0;
private static final int ARRAY_SIZE = 11;
MQDepth[] mqDepths = new MQDepth[ARRAY_SIZE];
String[] c = {"c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11"};
Timer timer;
public String getMQDepthJson() {
Gson gson = new Gson();
while(count < 11) {
MQDepth mq = new MQDepth();
int currentDepth = mq.calculateCurrentDepth();
mq.setCurrentDepth(currentDepth, c[count]);
mqDepths[count] = mq;
count++;
}
count = 0;
return gson.toJson(mqDepths);
}
@GET
@Path("/mqDepthJson")
@Produces("application/json")
public String runTask() {
while(true) {
Timer timer = new Timer();
timer.schedule(new MQDepthJson(), 10000);
return getMQDepthJson();
}
}
@Override
public void run() {
getMQDepthJson();
}
}
Java中没有内存泄漏。 您不必创建对象,而不必删除它们。 当对象超出范围时,将不再有对其的有效引用。 将来的某个时候,垃圾收集器将释放内存。
您可能在Java中意外地保留了对象。 在您的代码中存在这种可能性,因为您使用的是数组而不是ArrayList
。 在代码中,如果您不再需要mqDepths
数组中的MQDepth
, mqDepths
必须将数组该位置的值设置为null。 像这样
mqDepths[3] = null;
强烈建议您使用ArrayList
来处理数组。
垃圾收集器将稍后自动释放找不到参考变量的对象。 如果要显式进行垃圾回收,请使用System.gc()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.