[英]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.