我有一個包含一個按鈕的JFrame。當按鈕被點擊時,它打開了一個包含有大量文本的JTextPane的視窗。
- 在開始時,該應用程式占用了35mb的記憶體。
- 當新視窗被打開時,應用程式占用了大約 200 mb 的記憶體。
- 當新視窗關閉時,應用程式占用了價值約120 mb的記憶體。
package main;
import javax.swing.*;
import java.awt.*;
public class MemoryLeakTest {
public void start{
JFrame frame = new JFrame() 。
frame.setSize(500,500) 。
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)。
frame.setLocationRelativeTo(null)。
JButton button = new JButton("Create new window") 。
button.addActionListener(l->{
createWindow();
});
frame.add(button);
frame.setVisible(true)。
}
public void createWindow(){
window w = new window() 。
w.setVisible(true)。
}
public static void main(String[] args) {
new MemoryLeakTest().start()。
}
}
class window extends JFrame {
private JTextPane textPane;
public window() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)。
setSize(500, 500) 。
textPane = new JTextPane();
textPane.setText(extremelyLongText())。
add(textPane)。
System.out.println("新視窗創建!")。
}
public String extremelyLongText() {
StringBuilder builder = new StringBuilder()。
for (int j = 0; j < 1000; j , builder. append("
"))
for (int i = 0; i < 10000; i , builder. append("a")) ;
return new String(builder)。
}
@Override
public void dispose() {
super.dispose()。
textPane.setText("")。
System.gc();
textPane= null;
System.gc()。
}
我重寫了處置方法,將這個JTextPane設為null。我預計記憶體消耗會回落到35mb,但它只下降到120mb。為什么會出現這種情況?是不是JTextPane中的字串沒有得到垃圾收集?
我如何確保每當我使用JTextPane時記憶體被釋放出來?
編輯。 我在 Windows 10 上使用 jdk 16 來測驗這個問題,我在任務管理器上看到了記憶體的使用情況
uj5u.com熱心網友回復:不要指望System.gc()能強制執行gc。有些jvm在呼叫它時甚至什么都不做。jvm可以在它決定的任何時候進行gc。
uj5u.com熱心網友回復:
好吧,看起來沒有記憶體泄漏發生。
然而,當創建第一個視窗時,非堆記憶體明顯增加:
即使在創建了第2個視窗,甚至是第3個視窗之后,非堆記憶體仍然保持基本不變,所以我想這里并沒有什么問題。我不知道有什么方法可以釋放非堆記憶體,但我想可以說上面的代碼是正確的,沒有發生記憶體泄漏。 (雖然只有最后一個System.gc()的呼叫就足夠了)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310291.html
標籤:
上一篇:為什么我為JTextArea設定了游標位置后,文本會發生變化?
下一篇:QCoreApplication.postEvent(receiver,event)只有在輸入函式時才有好的結果。

