Fixed some possible race conditions