Skip to content

Commit 0215226

Browse files
committed
Cleanup after tests to avoid OOME: Metaspace in fast-run testOnly sequence
After these changes, this project no longer exhibits the problems discussed in sbt/sbt#2056
1 parent 70ff5cc commit 0215226

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

build.sbt

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@ def commonSettings: Seq[Setting[_]] = Seq(
2929
},
3030
publishArtifact in Compile := true,
3131
publishArtifact in Test := false,
32-
parallelExecution in Test := false
32+
parallelExecution in Test := false,
33+
testOptions in Test += {
34+
val log = streams.value.log
35+
Tests.Cleanup { loader => cleanupTests(loader, log) }
36+
}
3337
)
3438

3539
val mimaSettings = Def settings (
@@ -232,3 +236,21 @@ def customCommands: Seq[Setting[_]] = Seq(
232236
state
233237
}
234238
)
239+
240+
// TODO move into sbt-house-rules?
241+
def cleanupTests(loader: ClassLoader, log: sbt.internal.util.ManagedLogger): Unit = {
242+
// shutdown Log4J to avoid classloader leaks
243+
try {
244+
val logManager = Class.forName("org.apache.logging.log4j.LogManager")
245+
logManager.getMethod("shutdown").invoke(null)
246+
} catch {
247+
case _: Throwable =>
248+
log.warn("Could not shut down Log4J")
249+
}
250+
// Scala Test loads property bundles, let's eagerly clear then from the internal cache
251+
// TODO move into SBT itself?
252+
java.util.ResourceBundle.clearCache(loader)
253+
// Scala Test also starts TimerThreads that it doesn't eagerly cancel. This can weakly retain
254+
// metaspace until a full GC.
255+
System.gc()
256+
}

0 commit comments

Comments
 (0)