[英]BufferedReader.readLine() Creating threads()?
我正在尝试使一个服务器可以具有多个用户,即时消息仅创建2个线程,但是我的BufferedReader.readLine()似乎正在创建多个线程并导致OutOfMemory异常,我不明白为什么要这样做?
导致异常的函数:
public void run() {
try {
Username = Input.readLine();
} catch (IOException e1) {
disconnect();
}
String lastInput = null;
try {
while ((lastInput = Input.readLine()) != null) {
System.out.println(lastInput);
if (lastInput.startsWith("Chat: ")) {
sendToAllClients(lastInput.substring(7));
}
}
} catch (IOException e) {
disconnect();
}
}
例外:
Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
at java.lang.AbstractStringBuilder.append(Unknown Source)
at java.lang.StringBuffer.append(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Main.User.run(User.java:46)
at java.lang.Thread.run(Unknown Source)
注意:用户名= Input.readLine()使异常
为了避免无限循环并因此避免OOM异常:
try{
while ((currentInput=Input.readLine()) != null) {
if (currentInput.startsWith("Chat: "))
sendToAllClients(currentInput.substring(7));
}
catch (IOException e) { //bad to swallow exception: let's the method throw it or make something with it here}
readLine()不创建线程。
如果'lastInput'为null,则应退出循环并关闭流。
而且,如果您遇到异常,请记录或打印它,关闭流,然后中断。
Out of memory heap space
会导致程序陷入无限循环。
您的代码:
while (true) {
try {
lastInput = Input.readLine();
} catch (IOException e) {}
if (lastInput != null) {
System.out.println(lastInput);
if (lastInput.startsWith("Chat: ")) {
sendToAllClients(lastInput.substring(7));
}
}
表示循环内的代码将无限次运行,而没有任何条件充当退出条件。 即使出现问题:您也正在捕获该异常,并且代码继续在循环内继续进行。
这导致Out of Memory : Heap Space.
建议的解决方案:
while (true)
{
try
{
lastInput = Input.readLine();
}
catch (IOException e)
{
break;
}
if (lastInput != null)
{
System.out.println(lastInput);
if (lastInput.startsWith("Chat: "))
{
sendToAllClients(lastInput.substring(7));
}
}
}
用户输入引起异常的任何名称后,该循环就会中断(实际上是while循环的退出条件)
编辑
我认为可能是该问题的根源可能是:
lastInput.substring(7)
如果lastInput
字符串的大小很大,几乎可以填满系统上安装heap space of the JVM
的heap space of the JVM
则从第7th character to the last character
的substring
调用将在内部触发新String
的创建(因为Strings是不可变的) ),并且堆空间不足, substring
执行会产生OutOfMemory exception
。
首先:检查程序中while的循环。 第二:设置参数集JAVA_OPTS = -Xms32m -Xmx512m。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.