Use AutoCloseable and fix invalid implementation