improved error handling and locking