@@ -561,13 +561,19 @@ private Env createInitialEnv() {
561561
562562 private CpsScript parseScript () throws IOException {
563563 // classloader hierarchy. See doc/classloader.md
564- trusted = new CpsGroovyShellFactory (this ).forTrusted ().build ();
565- shell = new CpsGroovyShellFactory (this ).withParent (trusted ).build ();
564+ CpsScript s ;
565+ try {
566+ trusted = new CpsGroovyShellFactory (this ).forTrusted ().build ();
567+ shell = new CpsGroovyShellFactory (this ).withParent (trusted ).build ();
566568
567- CpsScript s = (CpsScript ) shell .reparse ("WorkflowScript" ,script );
569+ s = (CpsScript ) shell .reparse ("WorkflowScript" ,script );
568570
569- for (Entry <String , String > e : loadedScripts .entrySet ()) {
570- shell .reparse (e .getKey (), e .getValue ());
571+ for (Entry <String , String > e : loadedScripts .entrySet ()) {
572+ shell .reparse (e .getKey (), e .getValue ());
573+ }
574+ } catch (RuntimeException | Error x ) {
575+ closeShells ();
576+ throw x ;
571577 }
572578
573579 s .execution = this ;
@@ -1308,10 +1314,26 @@ synchronized void onProgramEnd(Outcome outcome) {
13081314 this .persistedClean = Boolean .TRUE ;
13091315 }
13101316
1317+ private void closeShells () {
1318+ try {
1319+ if (shell != null ) {
1320+ LOGGER .fine (() -> "closing main class loader from " + owner );
1321+ shell .getClassLoader ().close ();
1322+ shell = null ;
1323+ }
1324+ if (trusted != null ) {
1325+ LOGGER .fine (() -> "closing trusted class loader from " + owner );
1326+ trusted .getClassLoader ().close ();
1327+ trusted = null ;
1328+ }
1329+ } catch (IOException x ) {
1330+ LOGGER .log (Level .WARNING , "failed to close class loaders from " + owner , x );
1331+ }
1332+ }
1333+
13111334 void cleanUpHeap () {
13121335 LOGGER .log (Level .FINE , "cleanUpHeap on {0}" , owner );
1313- shell = null ;
1314- trusted = null ;
1336+ closeShells ();
13151337 if (scriptClass != null ) {
13161338 try {
13171339 cleanUpLoader (scriptClass .getClassLoader (), new HashSet <>(), new HashSet <>());
0 commit comments