Improve the shutdown logic.