Added lock as suggested in #789

Tried it 50 times without -> 20 runs crashed with NPE
Tried it 30 times with -> no crashes

I did not experience performance penalties, but maybe someone wants to verify that.

Fixes #789