com.databasesandlife.util.ResourceClosingIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-common Show documentation
Show all versions of java-common Show documentation
Utility classes developed at Adrian Smith Software (A.S.S.)
package com.databasesandlife.util;
import java.util.Iterator;
/**
* Wraps an Iterator, such that as soon as the iterator's hasNext method returns false, user-supplied code is executed.
* This can be used for closing JDBC Connections, Statements, etc.
*
* @author This source is copyright Adrian Smith and licensed under the LGPL 3.
* @see Project on GitHub
*/
public class ResourceClosingIterator implements Iterator {
Iterator source;
Runnable onClose;
boolean closingDone = false;
/** @param onClose to be run when the iterator's hasNext method returns false
* @param source the iterator to supply the data which will be returned from this iterator */
public ResourceClosingIterator(Runnable onClose, Iterator source) {
this.source = source;
this.onClose = onClose;
}
@SuppressWarnings("PointlessBooleanExpression")
public synchronized boolean hasNext() {
var result = source.hasNext();
if (result == false && closingDone == false) {
onClose.run();
closingDone = true;
}
return result;
}
public T next() {
return source.next();
}
public void remove() {
source.remove();
}
}