added a synchronized block to prevent race conditions