Improve shutdown handling