我的一个应用程序(一个基本的 IRC 工具)遇到以下问题,该工具使用“HTMLEditorKit”作为输出 GUI 将消息添加到“JTextPane”。我注意到,随着时间的推移,我的应用程序随机地使用越来越多的内存,在使用大约 20 分钟后,在拥挤的 channel 中很容易就爆炸到已经 300MB。我认为该问题在某种程度上与“JTextPane”有关,因为我可以使用以下代码重现该问题:
package javaapplication26;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Element;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
public class NewJFrame extends javax.swing.JFrame {
private long globalCount = 0;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
this.setSize(500, 200);
this.setLocationRelativeTo(null);
this.jTextPane1.setEditorKit(new HTMLEditorKit());
this.jTextPane1.setContentType("text/html");
this.jTextPane1.setText("<html><body><div id=\"GLOBALDIV\"></div></body></html>");
this.jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
this.jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
DefaultCaret caret = (DefaultCaret) this.jTextPane1.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
this.jScrollPane1.setAutoscrolls(false);
this.jTextPane1.setAutoscrolls(false);
Thread fillThread = new Thread() {
@Override
public void run() {
while (!interrupted()) {
try {
removeFromPane(jTextPane1);
insertHTMLToPane(jTextPane1, "<div>"+globalCount+"</div>");
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
break;
}
}
}
};
fillThread.start();
}
private void removeFromPane(JTextPane pane) {
HTMLDocument doc = (HTMLDocument) pane.getDocument();
Element element = doc.getElement("ID" + (this.globalCount - 10));
if (element != null) {
doc.removeElement(element);
}
}
private void insertHTMLToPane(JTextPane pane, String htmlCode) {
this.globalCount++;
HTMLDocument doc = (HTMLDocument) pane.getDocument();
Element element = doc.getElement("GLOBALDIV");
if (element != null) {
try {
doc.insertBeforeEnd(element, "<div id=\"ID"+this.globalCount+"\">" + htmlCode + "</div>");
} catch (BadLocationException | IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new java.awt.BorderLayout());
jScrollPane1.setViewportView(jTextPane1);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
奇怪的是,当让它在 Netbeans 中运行时,这种情况并不会 100% 发生。有时它保持在 70MB 左右并且永远不会增长,但再运行一次时,它会随机爆炸,一两分钟后已经增长到大约 200-250MB。
我真的不知道内存中的数据越来越多。似乎通过“doc.removeElement(element)”删除一行并不总是将其后面的对象标记为在下一个 GC 例程中清除。
让它使用探查器在 Netbeans 中运行,我得到如下信息:
似乎有某种“撤消机制”保留对所有插入行的引用?不过,我不是使用探查器的专家,因为我没有从中得到一些逻辑,即使程序中没有发生任何事情,像 char[] 和其他一些东西都会增长到数千个。
这似乎暗示,无论出于何种原因,JTextPane 都会为每个插入创建一个新的样式表并将其永远保留在哈希表中:
我欢迎任何帮助来找出发生这种情况的原因或如何解决该问题。当然,我在 Windows 10 下使用最新的 64 位 JDK。非常感谢
最佳答案
你的fillThread
真的很可怕而且毫无意义,为了 Activity ,请不要走那条路。
这个线程有点让我们吃资源
,除了java本身足够重之外,它确实会给系统带来很大的困惑。
您可以根据事件调用您的业务(删除最后一条消息并添加新消息),在这里您可以依靠单击按钮或在文本框中输入键。
即使您正在使用无状态的东西(例如http),您也可以将 sleep 时间增加到更有意义的时间,也许1秒,甚至更多。
一个可能的问题(我也经历过)可能是过度惰性的 GC。我不能说 100%,但是由于你的线程正在吃东西(繁重的工作),GC 找不到时间去获取内存。
即使JVM旁边表明它有线程GC,但它可能无法在内存上工作并有时并行释放数据(正如您也经历过的那样)。
您还可以检查您所说的 HashMap ,并确保所有需要添加和删除的数据都按预期完成。
此外,您的 globalCount
不是线程安全的,您可以使用 AtomicInteger
代替。
关于java - JTextPane/HTMLEditorKit 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44935134/