Fix possible deadlock when locking key files (9.16)

(cherry picked from commit be87edd2)

Closes #2786 (closed)

Merge request reports