By the definition of AutoCloseable
interface,
I must call close()
for ALL instances.
i.e. I must write like this.
try(A a = new A()){
//do something
}
In java.sound.sampled.SourceDataLine
interface,
or more commonly, in java.sound.sampled.Line
interface,
is it required to call close()
for ALL instances,
or I must call close()
ONLY AFTER open()
has called ?
If the official document explicitly states that I must close
only when isOpened
,
I want to write like this.
but I couldn't find mention.
//can I write like this ?
SourceDataLine sdl;
try{
sdl = AudioSystem.getSourceDataLine(audioFormat);
sdl.open(audioFormat,bufferSize);
}catch(LineUnavailableException ex){
throw new RuntimeException(null,ex);
}
try(SourceDataLine sdlInTryWithResources = sdl){
//do something
}
Your actual question should be “does it harm to call close()
when the data line has not been opened?” and the answer is “no”, so you can simply use
try(SourceDataLine sdl = AudioSystem.getSourceDataLine(audioFormat)) {
sdl.open(audioFormat, bufferSize);
// work with sdl
}
catch(LineUnavailableException ex) {
throw new RuntimeException(ex);
}
Note that javax.sound.sampled.Line
has been deliberately changed in Java 7 to extend AutoCloseable
, whose sole purpose is to allow the resource to be used within a try-with-resource statement.