Created
July 22, 2014 19:20
-
-
Save danieldietrich/5dcb3ecc5c1632720896 to your computer and use it in GitHub Desktop.
Exit the JVM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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(() -> println("hi"), 1000) | |
| * </code> | |
| * </pre> | |
| * | |
| * instead of | |
| * | |
| * <pre> | |
| * <code> | |
| * final Timer timer = new Timer(); | |
| * timer.schedule(new TimerTask() { | |
| * @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