强制显式删除Java对象 [英] Force explicit deletion of a Java object

查看:263
本文介绍了强制显式删除Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究处理大量密集流量的Java服务器。服务器接受来自客户端的数据包(通常为几兆字节)并将它们转发给其他客户端。服务器从不显式存储任何传入/传出数据包。但是服务器不断地运行到 OutOfMemoryException异常。例外。

我添加了 System.gc() 到服务器的消息传递组件中,希望内存将被释放。另外,我将JVM的堆大小设置为千兆字节。所以我的问题是这样的:我怎样才能确保兆字节的消息没有无限期排队(尽管没有需要的话)?有没有办法让我对这些对象调用delete来保证它们没有使用我的堆空间?

  try 
$ b while(true)
{
int r = generator.nextInt(100); //生成一个0到100之间的随机数
Object o = readFromServer。的readObject();
sum ++;
//如果随机数大于丢弃率,则将该对象发送给客户端,否则
//将丢弃
if(r> dropRate)
{
writeToClient.writeObject(o);
writeToClient.flush();
numOfSend ++;
System.out.printf(No。%d send \\\
,sum);
} // if

} // while
} // try


看看你的代码:你的每一个数据包到达或者是新创建的 ObjectInput / OutputStream 实例发送,如果是的话,他们是否正确关闭?如果不是,每次读/写后是否调用 reset()?对象流类保留对所有对象的引用(为了避免每次引用时重新发送同一对象),防止垃圾收集。我在10年前就遇到了这个确切的问题 - 实际上,我第一次使用探查器来诊断内存泄漏......


I'm working on a Java server that handles a LOT of very dense traffic. The server accepts packets from clients (often many megabytes) and forwards them to other clients. The server never explicitly stores any of the incoming/outgoing packets. Yet the server continually runs into OutOfMemoryException exceptions.

I added System.gc() into the message passing component of the server, hoping that memory would be freed. Additionally, I set the heap size of the JVM to a gigabyte. I'm still getting just as many exceptions.

So my question is this: how can I make sure that the megabyte messages aren't being queued indefinitely (despite not being needed)? Is there a way for me to call "delete" on these objects to guarantee they are not using my heap space?

        try
        {
           while (true)
            {
               int r = generator.nextInt(100);//generate a random number between 0 and 100
                Object o =readFromServer.readObject();
                sum++;
                // if the random number is larger than the drop rate, send the object to client, else
                //it will be dropped
                if (r > dropRate)
                {
                    writeToClient.writeObject(o);
                    writeToClient.flush();
                    numOfSend++;
                    System.out.printf("No. %d send\n",sum);
                }//if

            }//while
        }//try

解决方案

Looking at your code: are your ObjectInput/OutputStream instances newly created each time a packet arrives or is sent, and if so, are they closed properly? If not, do you call reset() after each read/write? The object stream classes keep a reference to all objects they have seen (in order to avoid resending the same object each time it is referred), preventing them from being garbage collected. I had that exact problem about 10 years ago - actually the first time I had to use a profiler to diagnose a memory leak...

这篇关于强制显式删除Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆