Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Created July 22, 2014 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldietrich/5dcb3ecc5c1632720896 to your computer and use it in GitHub Desktop.
Save danieldietrich/5dcb3ecc5c1632720896 to your computer and use it in GitHub Desktop.
Exit the JVM
/**
* Exits the JVM using {@code Runtime.getRuntime().exit(status)} (which is equivalent to
* {@code System.exit(0)}). If something goes wrong while running the finalizers and shutdown
* hooks, or the timeout is reached, the JVM is forced to be terminated by calling
* {@code Runtime.getRuntime().halt(status)}.
*
* @param status the exit status, zero for OK, non-zero for error
* @param timeout The maximum delay in milliseconds before calling
* {@code Runtime.getRuntime().halt(status)}.
*
* @see <a href="http://blog.joda.org/2014/02/exiting-jvm.html">exiting jvm</a>
*/
public static void exit(int status, long timeout) {
final Runtime runtime = Runtime.getRuntime();
try {
schedule(() -> runtime.halt(status), timeout);
runtime.exit(status);
} catch (Throwable x) {
runtime.halt(status);
} finally { // double-check
runtime.halt(status);
}
}
/**
* Syntactic sugar, allows to call
*
* <pre>
* <code>
* final Timer timer = Timers.schedule(() -&gt; println("hi"), 1000)
* </code>
* </pre>
*
* instead of
*
* <pre>
* <code>
* final Timer timer = new Timer();
* timer.schedule(new TimerTask() {
* &#64;Override
* public void run() {
* println("hi");
* }
* }, 1000);
* </code>
* </pre>
*
* @param task A Runnable
* @param delay A delay in milliseconds
* @return A Timer
*/
public static Timer schedule(Runnable task, long delay) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
task.run();
}
}, delay);
return timer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment