Github user stain commented on the issue:

    https://github.com/apache/incubator-commonsrdf/pull/24
  
    In order to close the `RepositoryConnection` (and `RepositoryResult`) I 
added an interface
    
    ``` java
    public interface ClosableIterable<T> extends java.util.Iterable<T>, 
AutoCloseable { }
    ```
    
    which is not very different from RDF4J's 
`org.eclipse.rdf4j.common.iteration.CloseableIteration` and 
`CloseableIterationIterator`; but can be used like this:
    
    ```java
    RDF4JGraph graph; // ..
    try (ClosableIterable<Triple> triples : graph.iterate()) {
       for (Triple t : triples) {
           return t; // OK to terminate for-loop early
       }
    }
    ```
    
    It will then close both the `RepositoryResult` and `RepositoryConnection`.
    
    It also closes on the last `.hasNext()` - but that is for convenience only 
for interoperability with `Graph.iterate()` interface, and would not happen if 
you break out of the for loop return early (as above).
    
    The only other alternatives to provide a somewhat transparent .iterate() 
with RDF4J (without the caller having to do say `.begin()` and `.end()`) I can 
think of would be either a `.finalize()` in the Iterator (but you won't know 
if/when it will run) and to consume the whole of the iteration in memory and 
expose a normal java.util.List iterator (which would consume lots of memory and 
fall over after 2G entries).
    
    Of course interoperability is already somewhat broken with my proposal here 
as the other `Graph.iterate()` are not (now) ClosableIterable and thus can't be 
used with the try-with-resources block like that.
    
    I updated `org.apache.commons.rdf.api.AbstractGraphTest` to avoid the RDF4J 
tests taking a long time (20s timeout pr test if the repository has unclosed 
connections). For the `.stream()` this was easy (`Stream` implements 
`AutoClosable`), but for the `Iterable` I had to do:
    
    ```java
    private void closeIterable(Iterable<Triple> iterate) throws Exception {
            if (iterate instanceof AutoCloseable) {
                ((AutoCloseable) iterate).close();
            }
    }
    ```



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

Reply via email to