我想在我的程序中使用线程播放音效,我搜索了网页,并且据我了解,当线程到达运行函数结束时,它将变成免费的GC搜集。线程不释放内存
但是,当我多次调用函数时,任务管理器显示内存使用量增加很多,并且它永远不会回落,我等待了2分钟的GC,但没有任何效果。
这里是我使用的播放音效代码:
public static void playSfx(final String path) {
new Thread(new Runnable() {
public void run() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(path));
final int BUFFER_SIZE = 128000;
SourceDataLine sourceLine = null;
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
if (sourceLine == null)
return;
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
audioInputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}).start();
}
我应该怎么做来收回失去的记忆?
是什么让你觉得内存是*丢失*?你不使用它,所以无论它看起来像分配还是空闲都没关系。所以,JVM和你的操作系统都不要求释放内存,除非你需要*它。 – Holger