0

Objective:

To pass data from incoming UDP datagrams to 4 threads waiting on their respective queues. The application is supposed to work non-stop for pumping traffic to a DUT and process the incoming messages. This is what I am doing:

1. Public byte[] receiveData = new byte[512]
2. receivePacket = new DatagramPacket(receiveData, 0 , receiveData.length)
[The above 2 steps are in constructor of the listener class]
3. while (1)
a. ApplicationStart.serversocket.receive(receivePacket)
b. recvData = new String(receivePacket.getData()
. 
. {Processing of data}
.

c. recvData = null

Problem:

The memory is continuously increasing. I suspect this is because it is waiting for GC to claim the unused memory. I wish I can allocate some static memory outside the infinite while loop. The problem I face if I do this is that the “receivePacket.getData()” returns a byte array and to work on the data, I need to convert it into a string. All the data is in text format (to be specific it is MGCP packets). Please suggest any way to make sure that the memory is not exhausted. I don’t want to manually call the garbage collector. I am not sure of the overhead for GC.

Thanks

4

2 回答 2

0

首先,您不需要手动调用 GC,而且这样做通常是个坏主意。

话虽如此,尚不清楚您所说的“内存不断增加”是什么意思。

如果您的意思是从外部观察到您的应用程序的内存分配正在增加,那是正常的。Java 将尽可能分配新对象,并且仅在没有立即可用空间时运行 GC。从外部看,JVM 似乎正在使用越来越多的内存。

如果您的意思是 JVM 报告它正在耗尽堆空间(即通过抛出 OutOfMemoryError),那么您就有问题了。但是,运行 GC并不能解决这个问题。相反,您需要运行 Java 内存分析器来查找泄漏源并修复它。

(背景:Java 内存泄漏与(例如)C/C++ 内存泄漏有点不同。在 C/C++ 中,当您的应用程序在不再需要时忽略free/一个对象,就会发生泄漏。在 Java 中,会发生内存泄漏delete当您的应用程序意外保留对不再使用的对象的引用时。如果 GC 认为应用程序可能会再次使用该对象,它就无法回收它......因此该对象仍然存在。)

于 2010-10-14T06:44:36.173 回答
0

出色地。我当然希望它的功课而不是离岸项目......

回答您的实际问题:

您可以创建多个预先分配的数据包,并将它们添加到队列中。从队列的开头抓取一个使用过的包,并接收到它。当处理程序线程处理完数据包时,它将它放在队列的后面。

应该避免步骤 3.b,因为它创建了一个新的字节数组并将数据包中的内容复制到其中,因此重写线程以处理数据包(或字节数组)作为输入。

您接收数据包的速度可能比您处理它们的速度快;然后您的代码将耗尽所有内存。(当您分配数据包和字符串并将它们放入处理程序线程的队列时。)

如果您正在使用阻塞队列,并等待“免费”数据包读入,那将不会发生;至少不是以同样的方式。UDP 数据包将在操作系统或 javas 网络堆栈的某处被丢弃或缓冲(或可能两者兼而有之),因此您需要注意这一点。这就是为什么大多数“面向消息”的协议最终都使用 TCP/IP,尽管它们实际上传输的是“数据报”

于 2010-10-14T10:47:45.737 回答