Code updated to be thread safe.