have an application that processes real-time data and is supposed to beep when a certain event occurs. The triggering event can occur multiple times per second, and if the beep
Memory leaks in Java have to do with objects that are still being referenced even after their useful lives have ended. In many cases, this will be due to something like repeatedly making 50 objects but only eliminating references to 49 of them later on.
Nothing like that seems to be going on in your code. Since prepareProcess()
only runs once, it's not highly suspect. That leaves playSound()
, which doesn't contain any object instantiation at all, much less a faulty reference elimination loop.
The caveat is that I'm not sure what goes on behind the scenes in your sound clip object, and it's hard to check because majuscule-C Clip
is only an interface. Unless you're using third-party code, though, I'd be very surprised to find a leak there.
Long story short, I wouldn't worry about it unless and until you actually see something like an OutOfMemoryError
.
yes, closing is necessary
myClip.addLineListener(new LineListener() {
public void update(LineEvent myLineEvent) {
if (myLineEvent.getType() == LineEvent.Type.STOP)
myClip.close();
}
});
or by
if (!myClip.isRunning())
myClip.close();
In my application (written before the advent of util.concurrent), this is the clip closing mechanism.
public static final Vector<Clip> vector = new Vector<Clip>();
static final int vector_size = 5;
// typically called before calling play()
static synchronized void consolidate() {
while (vector_size < vector.size()) {
Clip myClip = vector.get(0);
if (myClip.isRunning())
break;
myClip.close();
vector.remove(0);
}
if (vector_size * 2 < vector.size())
System.out.println("warning: audio consolidation lagging");
}
public static void play(final File myFile) {
try {
AudioInputStream myAudioInputStream = AudioSystem.getAudioInputStream(myFile);
final Clip myClip = AudioSystem.getClip();
vector.add(myClip);
myClip.open(myAudioInputStream);
myClip.start();
} catch (Exception myException) {
myException.printStackTrace();
}
}
As one of the comments suggest, it may delay the playback of new clips, but I cannot remember as a few ms delay were not important in my application.