Given a legacy code snippet with a threading bug, identify the race condition and refactor it to be thread-safe.