1

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
}  
  • try-with-resources was invented to clean your code up a bit, not to make it even more complicated... – tkausl Sep 04 '16 at 06:11

2 Answers2

0

It seems that you are overthinking things.

Just image try-with-resources would not exist and write down your code as you would have done prior Java 1.7.

For sure, you end up with something like:

Whatever somethingThatNeedsClosing = null;
try {
  somethingThatNeedsClosing = ...
  somethingThatNeedsClosing.whatever();
} catch (NoIdeaException e) {
  error handling
} finally {
  if (somethingThatNeedsClosing != null) {
    somethingThatNeedsClosing.close()
  }
}

Try-with-resources simply allows you to reduce this example accordingly.

In other words: try-with-resources allows you to define one (or more) resource(s) that will be used within the try block; and that will finally be closed. As in: each and any resource declared for try ... will be closed.

More specifically: don't think about other instances of your resource. Focus on the one that you are currently dealing with.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

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.

Holger
  • 285,553
  • 42
  • 434
  • 765