views:

225

answers:

1

The following code creates a new audio clip, plays it, sleeps for 3 seconds and then closes it when it is finished playing. Despite the call to close(), I am watching the memory usage of the jvm go up by the size of the sound clip every time the while loop is run.

I'm participating in a game coded in java, and am handling the sound. I cannot have the memory i'm using increase everytime a sound is played.

What am I missing?

Thanks! John

import java.io.File;
import javax.sound.sampled.*;

public class ClipLeak{

public static void main(String[] args) throws Exception{
 while(true){
  File soundFile = new File("./sound.wav");
  AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

  DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
  Clip clip = (Clip) AudioSystem.getLine(info);
  clip.open(sound);
                    sound.close();

  clip.addLineListener(new LineListener(){
   public void update(LineEvent event){
    if(event.getType() == LineEvent.Type.STOP){
     event.getLine().close();
    }
   }
  });

  clip.start();
  Thread.sleep(2000);
 }
}
}
A: 

If you are sure there is a memory leak and not a garbage collect delay, you could start with closing and cleaning up all resources you allocate, removing the listener and setting all references to null. (Move the File object out of the loop too.)

If that doesn't help and the javadocs don't hint at what can be cleared you can trigger a heapdump to see what objects use the memory and what their path to root is.

rsp
I let the loop run for about a minute and watched the memory climb and climb. If it was being garbage collected, I should see memory reduced along that minute right?
John
Not necessarily. The JVM only runs the GC when it feels like it.
Simon Righarts
That depends on how busy the rest of the code is, it might increase for a while before coming back down. The garbage collect cycle tends to display a jigsaw pattern. That's normal. Having said that you might want to close and clear the resources you use.
rsp