fixed multiple bugs to eliminate race conditions due to lack of atomicity