多次调用 geotools 的 SimpleFeatureCollection.features() 会导致 "Maximum lock count exceeded"

Calling geotools' SimpleFeatureCollection.features() one too many times results in "Maximum lock count exceeded"

我从 HDD 上的形状文件创建了一次 geotools' SimpleFeatureCollection。然后我多次调用它的 .features() 方法。到目前为止,我认为这是一种很好的做法,但事实似乎并非如此。多次调用特征方法后,我收到

Exception in thread "main" java.lang.Error: Maximum lock count exceeded
 at java.util.concurrent.locks.ReentrantReadWriteLock$Sync.fullTryAcquireShared(ReentrantReadWriteLock.java:528)
 at java.util.concurrent.locks.ReentrantReadWriteLock$Sync.tryAcquireShared(ReentrantReadWriteLock.java:488)
 at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireShared(AbstractQueuedSynchronizer.java:1282)
 at java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock.lock(ReentrantReadWriteLock.java:727)
 at org.geotools.data.shapefile.files.ShpFiles.acquireRead(ShpFiles.java:358)
 at org.geotools.data.shapefile.files.ShpFiles.getReadChannel(ShpFiles.java:789)
 at org.geotools.data.shapefile.shp.ShapefileReader.<init>(ShapefileReader.java:253)
 at org.geotools.data.shapefile.ShapefileSetManager.openShapeReader(ShapefileSetManager.java:51)
 at org.geotools.data.shapefile.ShapefileFeatureSource.getReaderInternal(ShapefileFeatureSource.java:263)
 at org.geotools.data.shapefile.ShapefileFeatureStore.getReaderInternal(ShapefileFeatureStore.java:124)
 at org.geotools.data.store.ContentFeatureSource.getReader(ContentFeatureSource.java:563)
 at org.geotools.data.store.ContentFeatureCollection.features(ContentFeatureCollection.java:165)

如何避免这种情况发生?这里有什么好的编码习惯?我是否应该在每次调用其 .features() 方法之前使用形状文件创建 SimpleFeatureCollection?任何见解将不胜感激。

正如 javadocs 明确指出的,您必须在使用后关闭 FeatureIterator,否则资源将耗尽或泄漏。您需要使用这样的代码:

FeatureIterator i = featureCollection.features()
 try {
    while( i.hasNext() ){
        SimpleFeature feature = i.next();
    }
 }
 finally {
    i.close();
 }