Added guards to prevent an infinite loop during shutdown