Correctly close the database after an atomic counter of connections goes to zero