All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.databasesandlife.util.ResourceClosingIterator Maven / Gradle / Ivy

There is a newer version: 21.0.1
Show newest version
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();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy