removing more duplicated code

Removing repetitive code and fixing data race.