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;
}
源碼來源:commons-dbcp2包中的BasicDataSource.getNumActive()。
解釋:connectionPool在判空之前將引用複製給局部變量,這樣即使之後另一個線程將connectionPool置爲null,垃圾回收器也不會回收connectionPool引用指向的對象,因爲局部變量的引用還存在,所以不會報空指針異常。在方法執行完之後,局部變量被釋放,此時connectionPool指向的對象纔可能會被垃圾回收器回收。