Fixing deadlock and thread-safety issues in handlers