java.lang.OutOfMemoryError: unable to create new native thread

通過翻譯獲取的中文直譯 => java.lang.OutOfMemoryError:無法創建新的本地線程

一、原因:

問題原因是創建太多線程,而能創建的線程數是有限制的。
溢出情況可分兩種:
1,請求線程數大於所能創建線程數
2,請求線程數小於所能創建線程數


二、解決問題:

請求線程數大於所能創建線程數 

相關參數:
MaxProcessMemory 指的是一個進程的最大內存,假設爲 3G
JVMMemory JVM內存,假設爲 1G
ReservedOsMemory 保留的操作系統內存,假設爲100MB
ThreadStackSize 線程棧的大小,Liunx默認1MB

JAVA在創建一個新的線程時,虛擬機在創建一個Thread對象同時創建一個 操作系統線程(ThreadStackSize),這個系統線程所使用的線程不是 JVMMemory(JVM內存)
系統剩餘內存 => ( MaxProcessMemory - JVMMemory - ReservedOsMemory )
系統線程創建數 => ( MaxProcessMemory - JVMMemory - ReservedOsMemory )/ ThreadStackSize
結論 => 當JVM內存越大,所能創建的線程就越少,就越容易 java.lang.OutOfMemoryError: unable to create new native thread 

請求線程數小於所能創建線程數

這種情況就是程序中有bug,導致創建大量不需要的線程或者線程沒有及時回收,那麼必須解決這個bug,修改參數是不能解決問題的。

異常代碼:
FileInputStream ips = null;
FileOutputStream ops = null;
try{
	ips = new FileInputStream(new File("D:/a.txt"));
	ops = new FileOutputStream(new File("D:/b.txt"));
}catch(Exception e){
	e.printStackTrace();
}finally {
	try{
		if(ips != null){
			ips.close();
		}

		if(ops != null){
			ops.close();
		}
	}catch(Exception e1){
		e1.printStackTrace();
	}	
}
這段代碼看起來沒多大問題,但是 ips.close() 時出現異常 , ops.close(); 就無法關閉。

優化後:
FileInputStream ips = null;
FileOutputStream ops = null;
try{
	ips = new FileInputStream(new File("D:/a.txt"));
	ops = new FileOutputStream(new File("D:/b.txt"));
}catch(Exception e){
	e.printStackTrace();
}finally {
	try{
		if(ips != null){
			ips.close();
		}
	}catch(Exception e1){
		e1.printStackTrace();
	}	

	try{
		if(ops != null){
			ops.close();
		}
	}catch(Exception e1){
		e1.printStackTrace();
	}	
}


PS:轉載請註明出處


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章