Do not hold lock when testing connection. Collapse nested if statements with &&.