refactor code and fix race condition