Cleanup detection code and thread locking