Adding locks and moving exception handling around.