Fixed race condition when closing connections