Iterator资源释放的重要性

在Java开发中,不及时释放资源可能导致程序卡死。本文通过一个实例展示了在使用Iterator遍历并处理数据后,忘记关闭Iterator导致删除操作无法执行的问题。修复方法是确保在完成迭代后正确关闭Iterator。养成良好编程习惯,及时释放不再使用的资源,可以避免类似问题的发生。
摘要由CSDN通过智能技术生成

最近在开发中使用了Iterator遍历,一开始没有养成释放资源的习惯。直到踩坑,上代码

public static void addDataWithNewField(SimpleFeatureType newType, Geometry geometry, Map fieldValueMap , Map newFields) throws IOException {
      String typeName = newType.getTypeName();
      // 更新模式
      FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(typeName);
      SimpleFeatureCollection collection = (SimpleFeatureCollection) featureStore.getFeatures();
     
      SimpleFeatureCollection copyCollection = copyFeatures(newType, collection, newFields);
       // 这里还存在引用所以不可能删除掉,会卡死
      dataStore.removeSchema(typeName);
      dataStore.createSchema(newType);
      featureStore = (FeatureStore)dataStore.getFeatureSource(typeName);
      featureStore.addFeatures(copyCollection);
       //追加要素
      appendFeature(newType, geometry, fieldValueMap);
  }
  public static SimpleFeatureCollection copyFeatures(SimpleFeatureType newType, SimpleFeatureCollection collection, Map newFields) {
      SimpleFeatureIterator iterator = collection.features();
      SimpleFeatureBuilder builder = new SimpleFeatureBuilder(newType);
      List<SimpleFeature> copyFeatures = new ArrayList<>();
      while (iterator.hasNext()) {
          SimpleFeature simpleFeature = iterator.next();
          Collection<Property> properties = simpleFeature.getProperties();
          Iterator<Property> propertyIterator = properties.iterator();
          while (propertyIterator.hasNext()) {
              Property property = propertyIterator.next();
              builder.set(property.getName(), property.getValue());
          }
          Set set = newFields.keySet();
          Iterator iterator1 = set.iterator();
          while (iterator1.hasNext()) {
              String key = (String) iterator1.next();
              builder.set(key, newFields.get(key));
          }
          SimpleFeature copyFeature = builder.buildFeature(null);
          copyFeatures.add(copyFeature);
      }
      // 这个资源一定要记得关闭
      iterator.close();
      return new ListFeatureCollection(newType, copyFeatures);
  }

在这段代码中dataStore是连接数据库获取空间表资源,一开始没有释放iterator删除操作卡死不动,释放后顺利执行后面的代码。特此记录一下,以后一定要养成释放不用的资源的好习惯。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值