0

I am working on a small java network program for instant messages using sockets. In the application the messages are read using the DataOutputStream's readUTF() method, which return a String object. So every time a new message is arrived or sent a new String object is created in the memory, which in turn consumes memory. After a long time of communication there are several String objects in the memory.

So is there any way I can avoid this or I should try some other way of recieving messages. I am very new to Java network programming and its concepts. Thanks. I have a very bad coding style still I will try to make the question clear.

String recievedMessage = dataInputStream.readUTF();
String messageType = recievedMessage.substring(0, recievedMessage.indexOf("##"));
String message = recievedMessage.substring(recievedMessage.indexOf("##") + 2, recievedMessage.indexOf("$$"));

After this the message object is inserted in a JTextPane using a StyledDocument.

4

2 回答 2

2

这并非特定于网络编程:创建瞬态字符串几乎不需要任何成本,并且可以有效地进行垃圾收集。如果您将整个对话记录保留在 RAM 中,那么您开始遇到问题的唯一一点就是。如果您确实需要保存脚本,只需将所有消息转发到一个文件,而不保留 RAM。

于 2013-01-26T15:00:04.307 回答
0

它是什么类型的网络,例如面向连接或连接较少?你有内存问题吗?但我相信当数据包从点到点发送时,它会根据消息类型消耗一些内存,然后应该将其标记为垃圾收集。如果您提及您到底有什么问题,那就太好了。

于 2013-01-26T15:03:39.793 回答