try-with-resource to prevent resource leaks

(cherry picked from commit 39f775c38126bb25a0418f82196caaba463f8c1c)