Moved a lock, to hopefully eliminate race-conditions