java - Good way to close multiple resources across multiple methods -
i have class uses multiple closeable resources, opens them in constructor , want them closed in close() (inherited closeable interface) method. want use class in try-with-resources block similar java.io classes.
example (this not actual code, shows problem 2 resources):
public class foo implements closeable { private final reader first; private final reader second; public foo(reader first, reader second) { this.first = first; this.second = second; } ...
@override public close() throws ioexception { first.close(); second.close(); } } the above code not correct, because if first.close() throws exception, second won't closed. adding try/finally around pita , if have more of unmanageable.
basically question is: there library closing of multiple resources , logs exceptions , throws away last 1 found?
i looked @ multiple (guava closeables, ioutils.closequitly()) deal 1 resource, provide collection of those.
i haven't tested code, should work number of readers or other closable classes
package com.ggl.testing; import java.io.closeable; import java.io.filenotfoundexception; import java.io.filereader; import java.io.ioexception; import java.io.reader; import java.util.arraylist; import java.util.list; public class foo implements closeable { private final reader first; private final reader second; private list<exception> exceptions; public foo() { this.exceptions = new arraylist<>(); this.first = createreader("first.txt"); this.second = createreader("second.txt"); printexceptions(); } private reader createreader(string filestring) { try { return new filereader(filestring); } catch (filenotfoundexception e) { exceptions.add(e); return null; } } @override public void close() throws illegalstateexception { exceptions.clear(); closereader(first); closereader(second); printexceptions(); if (exceptions.size() > 0) { throw new illegalstateexception(); } } private void closereader(reader reader) { try { if (reader != null) { reader.close(); } } catch (ioexception e) { exceptions.add(e); } } private void printexceptions() { (int = 0; < exceptions.size(); i++) { exceptions.get(i).printstacktrace(); } } }
Comments
Post a Comment