逗人,
运行一段时间后我的java应用程序抛出异常
线程中的异常"线程-6" java.lang.OutOfMemoryError:超出GC开销限制
使用jprofiler监视jvm内存后,我发现代码中存在内存泄漏。
在我的程序中,我向一些设备发送了很多snmp请求并获取响应并将它们推送到两个LinkedBlockingQueue对象中。
有一些线程从队列中轮询并处理它们并从队列中删除对象。但似乎对象不会从队列中删除。我的代码中没有任何问题。
任何建议和意见将不胜感激
ResponseListener.java
public class ResponseListener{
public void receiveResponse(){
SNMPResultMessage resultMessage;
resultMessage = new SNMPResultMessage(
userObject.getDeviceId(),
oid,
deviceServiceId,
sensorId,
response.getVariable(oid).toInt(),
userObject.getTimestamp(),
Utils.getCreateDay(dt),
Utils.getQuarterOfDay(dt),
slaDisabled
);
Logger.debug("SNMP Request Response:" + resultMessage);
PubSub.publish(resultMessage);
}
}
PubSub.java
公共类PubSub {
public static final BlockingQueue<ResultMessage> average = new LinkedBlockingQueue<>();
public static final BlockingQueue<ResultMessage> cassandra = new LinkedBlockingQueue<>();
public static void publish(ResultMessage message) {
average.add(message);
cassandra.add(message);
}
private PubSub() {
/* prevent instantiation */
}
}
AverageWatcher.java
public class AverageWatcher implements Runnable{
@Override
public void run() {
try {
while (true) {
ResultMessage message = PubSub.average.take();
if (message == null) {
if (numberOfChanges > 1000) {
insertBatch();
}
continue;
}
numberOfChanges++;
if (changes.get(message.getSensorId()) == null) {
changes.put(message.getSensorId(), new HashSet<>());
}
changes.get(message.getSensorId()).add(new CreateDayQuarterOfDay(message.getCreateDay(), message.getQuarterOfDay()));
if (numberOfChanges > 5000) {
insertBatch();
}
}
} catch (Exception ex) {
Logger.error(ex.getCause());
}
}
}
CassandraQueueWatcher.java
public class CassandraQueueWatcher implements Runnable{
@Override
public void run() {
try {
while (true) {
ResultMessage message = PubSub.cassandra.take();
if (message == null) {
if (batchSize > 1000) {
insertBatch();
}
continue;
}
boolean violated = checkViolated(message);
batch.add(
Cassandra.insertRawReportStmt
.bind()
.setInt("sensor_id", message.getSensorId())
.setInt("create_day", message.getCreateDay())
.setLong("create_time", message.getTimestamp() / 1000)
.setFloat("value", message.getValue())
.setBool("violated",violated)
);
batchSize++;
if (batchSize > 2000) {
insertBatch();
}
message = null;
}
} catch (Exception ex) {
Logger.error(ex.getCause());
}
}
}
在我的代码中,仅在ResponseListener.java中创建新的SNMPResultMessage对象。请看一下附图。 jprofiler