Look into addShutdownHook and signals.