TRQ-2682. Fix a crash as well as a deadlock scenario.

I'm not sure that the deadlock scenario I'm fixing is the one for TRQ-2682 but it is
possible.