<commit_before>---
layout: post
title: Catching an interrupt and adding a shutdown hook in Scala.
tags: [Scala]
---

When using a
[JVM language](https://en.wikipedia.org/wiki/List_of_JVM_languages),
[shutdown hooks](http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)
are called before the VM shuts down.
They are also used to catch user interrupts
caused by Ctrl-C, for example.

In Scala specifically, this process is similar to the references above.
However, I'm writing this post because
I struggled finding a specific example to bootstrap from.

The `addShutdown` method is defined in Scala's
[sys](http://www.scala-lang.org/api/current/index.html#scala.sys.package)
package. It registers a shutdown hook and returns the Thread it created.
[The thread](http://www.scala-lang.org/api/current/index.html#scala.sys.ShutdownHookThread)
it returns is able to unregister itself, if desired.

The parameter to `addShutdownHook` is a by-name parameter.
See the [Scala Reference](http://www.scala-lang.org/docu/files/ScalaReference.pdf)<commit_msg>Correct link in Scala shutdown post.<commit_after>---
layout: post
title: Catching an interrupt and adding a shutdown hook in Scala.
tags: [Scala]
---

When using a
[JVM language](https://en.wikipedia.org/wiki/List_of_JVM_languages),
[shutdown hooks](http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread))
are called before the VM shuts down.
They are also used to catch user interrupts
caused by Ctrl-C, for example.

In Scala specifically, this process is similar to the references above.
However, I'm writing this post because
I struggled finding a specific example to bootstrap from.

The `addShutdown` method is defined in Scala's
[sys](http://www.scala-lang.org/api/current/index.html#scala.sys.package)
package. It registers a shutdown hook and returns the Thread it created.
[The thread](http://www.scala-lang.org/api/current/index.html#scala.sys.ShutdownHookThread)
it returns is able to unregister itself, if desired.

The parameter to `addShutdownHook` is a by-name parameter.
See the [Scala Reference](http://www.scala-lang.org/docu/files/ScalaReference.pdf)
{'fraction_non_alphanumeric': 0.10617059891107078, 'fraction_numerical': 0.0009074410163339383, 'mean_word_length': 4.88, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4613858', 'n_tokens_mistral': 693, 'n_tokens_neox': 659, 'n_words': 228}