2

Example:

try(ResultSet rs = DriverManager.getConnection(url, us, pw).createStatement().executeQuery(sql)) {

    //mycode
}

I don't have any reference to Connection or Statement, will they be closed too and if they do what is the order?

thanks

M A
  • 71,713
  • 13
  • 134
  • 174
  • See this question for a discussion on the topic: http://stackoverflow.com/questions/12552863/correct-idiom-for-managing-multiple-chained-resources-in-try-with-resources-bloc – thst Feb 09 '16 at 22:10

1 Answers1

3

According to the language specification, it will only close the ResultSet object. This is because the try-with-resources statement makes use of a resource specification where a resource is declared using a variable:

TryWithResourcesStatement:

try ResourceSpecification Block [Catches] [Finally]

ResourceSpecification:

( ResourceList [;] )

ResourceList:

Resource {; Resource}

Resource:

{VariableModifier} UnannType VariableDeclaratorId = Expression

Community
  • 1
  • 1
M A
  • 71,713
  • 13
  • 134
  • 174
  • 1
    is this correct: the resources in my code will be closed Automatically by closing the only available reference which is ResultSet rs, similar to the fact that resources which were Wrapped by other resources like: new OutputStream(new FileOutputStream()) FileOutputStream will be closed Automatically by closing OutputStream –  Feb 11 '16 at 15:01
  • 1
    @Seyjowzeetaapoogiukaagee No it's not correct. Closing `ResultSet` does not close a `Statement` nor the `Connection`. – M A Feb 11 '16 at 16:23
  • 1
    what about nested streams? will the wrapped streams be closed if try-with-resource statement close the outermost stream –  Feb 11 '16 at 18:08
  • 1
    Yes usually the wrapped streams are closed automatically. – M A Feb 12 '16 at 10:53