Various cleanups and thread-safety.