Closing InitialContext vs initialising it to null

228 views Asked by At

A little bit confused - lets say we create InitialContext and DataSource like this:

InitialContext ctx = new InitialContext();
DataSource ds = ((DataSource) ctx.lookup("jdbc/hsqldb"));

Now when some database operations are made, I suggest ctx should be closed:

 if (ctx != null) {
     ctx.close();
    }

But here InitialContext is simply initialised to null:

import java.sql.*;
import javax.sql.*;
import javax.ejb.*;
import javax.naming.*;

public class DistributedTransactionBean implements SessionBean {

    // ...

    public void ejbCreate() throws CreateException {

        ctx = new InitialContext();
        ds = (DataSource)ctx.lookup("jdbc/distCoffeesDB");
    }

    public void updateTotal(int incr, String cofName, String username,
                            String password)
        throws SQLException {

        Connection con;
        PreparedStatement pstmt;

        try {
            con = ds.getConnection(username, password);
            pstmt = con.prepareStatement("UPDATE COFFEES " +
                        "SET TOTAL = TOTAL + ? " +
                        "WHERE COF_NAME = ?");
            pstmt.setInt(1, incr);
            pstmt.setString(2, cofName);
            pstmt.executeUpdate();
            stmt.close();
        } finally {
            if (con != null) con.close();
        }
    }

    private DataSource ds = null;
    private Context ctx = null;
}

So what is happening when ctx is initiliased to null without closing it?

1

There are 1 answers

4
krisp On

When do you think "ctx is set to null" ?

From the code you provided it looks that ctx is not "set to null", it is initialised to null.

Then (after initialisation) during creation of the bean, ejbCreate() is called and reference to InitialContext is assigned:

ctx = new InitialContext();