Moved locking code into try block (thanks KT)