fixing race condition in the code