Slight modifications to #3 to prevent potential race conditions.