Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

On jvm IOApp clean exit, optionally print non-daemon threads #1379

Merged
merged 3 commits into from
Nov 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ private[effect] object IOAppPlatform {
// Return naturally from main. This allows any non-daemon
// threads to gracefully complete their work, and managed
// environments to execute their own shutdown hooks.
()
if (NonDaemonThreadLogger.isEnabled())
new NonDaemonThreadLogger().start()
else
()
} else {
sys.exit(code)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright (c) 2017-2019 The Typelevel Cats-effect Project Developers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats.effect.internals

import cats.syntax.all._
import scala.collection.mutable.ListBuffer

private[internals] object NonDaemonThreadLogger {

/** Whether or not we should check for non-daemon threads on jvm exit */
def isEnabled(): Boolean =
Option(System.getProperty("cats.effect.logNonDaemonThreadsOnExit")).map(_.toLowerCase()) match {
case Some(value) => value.equalsIgnoreCase("true")
case None => true // default to enabled
}

/** Time to sleep between checking for non-daemon threads present */
def sleepIntervalMillis: Long =
Option(System.getProperty("cats.effect.logNonDaemonThreads.sleepIntervalMillis"))
.flatMap(time => Either.catchOnly[NumberFormatException](time.toLong).toOption)
.getOrElse(10000L)
}

private[internals] class NonDaemonThreadLogger extends Thread("cats-effect-nondaemon-thread-logger") {

setDaemon(true)

override def run(): Unit = {
var done = false
while (!done) {
Thread.sleep(NonDaemonThreadLogger.sleepIntervalMillis)

val runningThreads = detectThreads()
if (runningThreads.isEmpty) {
// This is probably impossible, as we are supposed to be a *daemon* thread, so the jvm should exit by itself
done = true
} else {
printThreads(runningThreads)
}

}
}
private[this] def detectThreads(): List[String] = {
val threads = Thread.getAllStackTraces().keySet()
val nonDaemons = ListBuffer[String]()
threads.forEach { t =>
if (!t.isDaemon)
nonDaemons += s" - ${t.getId}: ${t}"
}
nonDaemons.toList
}

private[this] def printThreads(threads: List[String]) = {
val msg = threads.mkString("Non-daemon threads currently preventing JVM termination:", "\n - ", "")
System.err.println(msg)
}
}