From 26a42bd2034a7ecb1e5bd0f0dfbd179a2185502a Mon Sep 17 00:00:00 2001 From: Stefan Bodewig Date: Thu, 3 Sep 2009 07:06:58 +0000 Subject: [PATCH] clean up classloaders if things go wrong as well git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@810790 13f79535-47bb-0310-9956-ffa450edef68 --- .../ant/filters/util/ChainReaderHelper.java | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/org/apache/tools/ant/filters/util/ChainReaderHelper.java b/src/main/org/apache/tools/ant/filters/util/ChainReaderHelper.java index 068a5580b..41ba53b1f 100644 --- a/src/main/org/apache/tools/ant/filters/util/ChainReaderHelper.java +++ b/src/main/org/apache/tools/ant/filters/util/ChainReaderHelper.java @@ -24,6 +24,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import java.util.Vector; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; @@ -138,6 +139,8 @@ public final class ChainReaderHelper { final int filtersCount = finalFilters.size(); if (filtersCount > 0) { + boolean success = false; + try { for (int i = 0; i < filtersCount; i++) { Object o = finalFilters.elementAt(i); @@ -155,8 +158,8 @@ public final class ChainReaderHelper { } else { AntClassLoader al = pro.createClassLoader(classpath); - clazz = Class.forName(className, true, al); classLoadersToCleanUp.add(al); + clazz = Class.forName(className, true, al); } if (clazz != null) { if (!FilterReader.class.isAssignableFrom(clazz)) { @@ -208,16 +211,19 @@ public final class ChainReaderHelper { setProjectOnObject(instream); } } + success = true; + } finally { + if (!success && classLoadersToCleanUp.size() > 0) { + cleanUpClassLoaders(classLoadersToCleanUp); + } + } } final Reader finalReader = instream; return classLoadersToCleanUp.size() == 0 ? finalReader : new FilterReader(finalReader) { public void close() throws IOException { FileUtils.close(in); - for (Iterator it = classLoadersToCleanUp.iterator(); - it.hasNext(); ) { - ((AntClassLoader) it.next()).cleanup(); - } + cleanUpClassLoaders(classLoadersToCleanUp); } protected void finalize() throws Throwable { try { @@ -245,6 +251,15 @@ public final class ChainReaderHelper { project.setProjectReference(obj); } + /** + * Deregisters Classloaders from the project so GC can remove them later. + */ + private static void cleanUpClassLoaders(List/**/ loaders) { + for (Iterator it = loaders.iterator(); it.hasNext(); ) { + ((AntClassLoader) it.next()).cleanup(); + } + } + /** * Read data from the reader and return the * contents as a string.