Search code examples
javaapache-commons-dbcp

Copy reference to avoid NPE if close happens after null check?


This is the source code of commons-dbcp2, why can it avoid NPE?

public int getNumActive() {
    // Copy reference to avoid NPE if close happens after null check
    GenericObjectPool<PoolableConnection> pool = connectionPool;
    if (pool != null) {
        return pool.getNumActive();
    }
    return 0;
}

Solution

  • Notice the variable connectionPool is copied into a new variable pool. This pattern of copying references and using the new ref is used when there is chances of multithreading* and the original variable (connectionPool) being overwritten/cleared by a different thread.

    In this case, if there are two threads, one calling close method and other calling getNumActive method, then it is possible that first close method clears the connectionPool variable then getNumActive method attempts to run.

    If that case happens then even though the original variable clears, its copy (pool) survives. So pool.getNumActive(); never causes an NPE

    *In very sloppy terms