1

I'm trying to implement the following code in Java EE 8 (Java 11) to access a datasource in Wildfly 20. The objective is to close implicitly the JNDI context and the SQL connection:

try (InitialContext context = new InitialContext();
     Connection conn = ((DataSource) context.lookup(pool)).getConnection()) {
    
      // use the connection

} 
catch (NamingException e) {
    logger.error(e.getMessage());
} 
catch (SQLException e) {
    logger.error(e.getMessage());
}

Problem is that context is not closeable, as I get the compilation error:

The resource type InitialContext does not implement java.lang.AutoCloseable

I'm trying to avoid adding finally to close the context, is there a way to achieve this?

ps0604
  • 1,227
  • 23
  • 133
  • 330

1 Answers1

3

Try-with-resources works only with objects that are AutoCloseable. One way to do this without using finally is by wrapping the InitialContext in a wrapper that implements AutoCloseable that performs the necessary action in its close() method. Something like this:

public class AutoCloseableWrapper implements AutoCloseable {

    private final InitialContext context;

    public AutoCloseableWrapper(InitialContext context) {
        this.context = context;
    }

    public InitialContext getContext() {
        return this.context;
    }

    @Override
    public void close() throws Exception {
        this.context.close();
    }
}

Use it like this:

try (AutoCloseableWrapper wrapper = new AutoCloseableWrapper(new InitialContext());
     Connection conn = ((DataSource) wrapper.getContext().lookup(pool)).getConnection()) {

    // ...
}
Jesper
  • 202,709
  • 46
  • 318
  • 350