some thread safety and cleanup