Tighten the shutdown code to avoid potential NPEs