Skip to content

Commit

Permalink
Cleanup after tests to avoid OOME: Metaspace in fast-run testOnly seq…
Browse files Browse the repository at this point in the history
…uence

After these changes, this project no longer exhibits the problems
discussed in sbt/sbt#2056
  • Loading branch information
retronym committed Jul 13, 2018
1 parent 70ff5cc commit 0215226
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ def commonSettings: Seq[Setting[_]] = Seq(
},
publishArtifact in Compile := true,
publishArtifact in Test := false,
parallelExecution in Test := false
parallelExecution in Test := false,
testOptions in Test += {
val log = streams.value.log
Tests.Cleanup { loader => cleanupTests(loader, log) }
}
)

val mimaSettings = Def settings (
Expand Down Expand Up @@ -232,3 +236,21 @@ def customCommands: Seq[Setting[_]] = Seq(
state
}
)

// TODO move into sbt-house-rules?
def cleanupTests(loader: ClassLoader, log: sbt.internal.util.ManagedLogger): Unit = {
// shutdown Log4J to avoid classloader leaks
try {
val logManager = Class.forName("org.apache.logging.log4j.LogManager")
logManager.getMethod("shutdown").invoke(null)
} catch {
case _: Throwable =>
log.warn("Could not shut down Log4J")
}
// Scala Test loads property bundles, let's eagerly clear then from the internal cache
// TODO move into SBT itself?
java.util.ResourceBundle.clearCache(loader)
// Scala Test also starts TimerThreads that it doesn't eagerly cancel. This can weakly retain
// metaspace until a full GC.
System.gc()
}

0 comments on commit 0215226

Please sign in to comment.