TSS翻譯:常見的Java記憶體問題第一部分
原文連結:http://www.theserverside.com/news/thread.tss?thread_id=62217
http://blog.dynatrace.com/2011/04/20/the-top-java-memory-problems-part-1/
記憶體和垃圾收集器一直是Java應用程式最值得關注的問題之一。當我們對java有JVM的記憶體收集機制而津津樂道的時候,恐怕大多數人又對GC垃圾收集的機制莫諱如深。dynaTrace的Michael Kopp 也有同感,不過他把引起java記憶體流失的主要原因列出來了。
1、線程局部變數 Thread Local Variables
主要是在使用線程池的情況下容易出現,使用heap dump 容易找出問題所在;
2、可變的靜態欄位和集合Mutable static fields and collections
避免這種情況的很簡單少用。A good architectural rule is not to use
mutable static objects at all, most of the time there is a better alternative.
3、迴圈和複雜的雙向引用Circular and complex bi-directional references
對方舉了一個經典的例子:
org.w3c.dom.Document doc =
readXmlDocument();
org.w3c.dom.Node child =
doc.getDocumentElement().getFirstChild();
doc.removeNode(child);
doc = null;
4、JNI記憶體流失 JNI memory leaks
用的不多,不多說了。
5、類的
Equals/hashcode 不正確的實現
這樣的類使用HashMap容易的時候容易出問題。
避免這種情況的方法是做測試,比如這個工具:http://code.google.com/p/equalsverifier/
6、類載入器引起的記憶體流失
Class Loader 的層面比較底層,一般是應用程式伺服器和OSGi 容器中容易出現。
也許回複更精彩,把1,2,6綜合起來了:
static ThreadLocal myWrapper =
new ThreadLocal() {
NotThreadSafeObject initialValue() {
return new NotThreadSafeObject();
}
}
…
myWrapper.get().someMethod()
…
More details at http://www.szegedi.org/articles/memleak.html
如何使用:dynaTrace 見這裡:
http://blog.dynatrace.com/2011/04/13/application-performance-monitoring-in-production-a-step-by-step-guide/