refactor to prevent race condition