fix potential race condition, cleanup