Scala Shutdown fails?

Skydakok for sys.addShutdownHook

says shutdown hooks are NOT guaranteed to be run

. Now, this is perfectly reasonable, as the JVM is unlikely to be able to trigger shutdown hooks if you send the JVM to SIGKILL or whatever Windows equivalent.

However, stop hooks added with sys.addShutdownHook

never run, although the ones that work with Runtime.getRuntime.addShutdownHook

do.

Test -

scala> val t = new Thread { override def run = println("hi!") }
t: java.lang.Thread = Thread[Thread-4,5,main]

scala> Runtime.getRuntime.addShutdownHook(t)

scala> hi!
george@george-MacBook:~$ scala

      

(Missing startup message)

scala> val t = new Thread { override def run = println("hi!") }
t: java.lang.Thread = Thread[Thread-4,5,main]

scala> sys.addShutdownHook(t.run _)
res0: scala.sys.ShutdownHookThread = Thread[shutdownHook1,5,main]

scala> george@george-MacBook:~$

      

The documentation says, "The hook is automatically registered: the return value can be ignored", so there is no need to add the stream returned sys.addShutdownHook

 (and, anyway, throws an "IllegalArgumentException: Hook previously registered").

Also, calling run on the thread returned by addShutdownHook doesn't seem to do anything that is suspicious.

+3


source to share


1 answer


A typical signature addShutdownHook

is ( source ):

def addShutdownHook(body: => Unit): ShutdownHookThread

      

So, it's obvious why your code isn't working. What is expected is the call-by-name argument => Unit

, and you pass t.run _

that which returns () => Unit

is something else entirely.

Call-by-name parameters are not triggered until they are executed, passing t.run _

to mean that the function is created at the time the call-by-name argument is invoked - you don't pass the function itself instead of the call-by-name argument.



Using

sys.addShutdownHook(t.run)

      

instead of this. Or don't use thread at all and just pass the code to be executed:

sys.addShutdownHook(println("hi"))

      

+13


source







All Articles