refactored and fix race condition