SPARK-1656: Fix otential resource leaks

JIRA: https://issues.apache.org/jira/browse/SPARK-1656