我的 java 应用程序有内存泄漏 - 当我的资源清除代码正在执行任务管理器时显示内存使用没有改变。我的代码
while (isRunning) {
try
{
selector.select();
long sum=0;
Set keys = selector.selectedKeys();
Iterator it = keys.iterator();
while(it.hasNext())
{
SelectionKey key = (SelectionKey)it.next();
if (key.isReadable())
{
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer bb;
if(key.attachment()==null)
{
bb = ByteBuffer.allocate(1024*1024);
key.attach(bb);
}
else
{
bb = (ByteBuffer)key.attachment();
bb.clear();
}
int x = sc.read(bb);
System.out.println(x +" bytes were read");
if(x==-1)
{
key.attach(null); //doesn't work
sc.close();
//bb = null; // also doesn't work
}
}
}
keys.clear();
}
catch (Exception ex)
{
ex.printStackTrace(new PrintStream(System.out));
}
finally
{
//stopServer();
}
}
测试逻辑 - 我编写了简单的 TCP 客户端 java 程序,向服务器发送 100 条消息。我故意为每个连接分配了大缓冲区 - 1MB。当客户完成他的工作int x = sc.read(bb);
时返回 -1 并执行以下代码:
if(x==-1)
{
key.attach(null); //doesn't work
sc.close();
//bb = null; // also doesn't work
}
我用调试输出检查了它,这段代码确实执行了,但任务管理器仍然显示大量内存使用。问题出在哪里?