/* Copyright (c) 2007 John R. Rose Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //package java.lang; // some day? public class NonLocalExit { /** An exit point is accessible only in the thread where it was created, and only until it is closed. * If the system property java.lang.NonLocalExit.NOCHECK is not true, * then accessibility is checked before throwing. * If it is true, some checking overheads may be removed, but * jumping to an inaccessible exit point will lead to uncaught throws. */ final static boolean NOCHECK = Boolean.getBoolean("java.lang.NonLocalExit.NOCHECK"); /** If the system property java.lang.NonLocalExit.TRACE is true, * then a stack trace is filled in on every non-local jump. * This is expensive, but may (rarely) be helpful when debugging complex control flow. * (Expensive means that a null benchmark may slow down by * Note that NOCHECK controls debugging features that are more commonly helpful. */ final static boolean TRACE = Boolean.getBoolean("java.lang.NonLocalExit.TRACE"); /** The main reason this is public is to allow clients of {@link NonLocalExit} to write catches on it. *

It is also subclassable, so that a subclass of {@link NonLocalExit} can override * the factory method {@link NonLocalExit#makeJump() makeJump}. * This might allow an ingenious client to sharpen the type of the catch clause * at the end of the {@link NonLocalExit NonLocalExit’s} scope. */ public static class Jump // Might want to be a simple Throwable (or Error), since there is // a tendency for user code to catch RuntimeExceptions indiscriminately. extends RuntimeException implements Cloneable { // no public members: protected Jump() { } protected Jump clone() { // the usual clone pattern... try { return (Jump) super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError(); } } // nested in here to get lazy creation of the first Jump: static final Jump INSTANCE = TRACE ? null : new Jump(); } /** This is called by {@link #jump()} to create the throwable which my scope will catch. * An ingenious client might override this so as to use a sharper exception type * when there are overlapping and independent non-local returns in a program. * This is not the common case, though. The ingenious client should consider * using {@link Jump#clone() clone} of a pre-allocated subclass instance, in order * to avoid the high cost of {@link Throwable#fillInStackTrace() Throwable.fillInStackTrace}. */ protected Jump makeJump() { return TRACE ? new Jump() : // call fillInStackTrace ! Jump.INSTANCE.clone(); } /** Accessibility is limited to the current thread, * and (when I go out of scope) is set to null to indicate no access. */ // This variable is only used if checking is enabled, protected Thread scope; /** The most recent exception created to throw at me is stored here. * It is used to distinguish that jump from other jumps to similar scopes. * It starts out a null. I can be jumped to any number of times, * but only one jump will succeed. */ protected Jump jump; private void initState() { this.scope = Thread.currentThread(); } private void checkState() { Thread scope = this.scope; if (scope != Thread.currentThread()) { lose(scope, this.jump); } } // Bulky and rarely-used method to produce a helpful error message. // Do not inline into checkState. private static void lose(Thread scope, Jump jump) { if (scope != null) throw new IllegalStateException("cannot jump to another thread "+scope); if (jump != null) throw new IllegalStateException("cannot jump twice to the same target ", jump); throw new IllegalStateException("illegal jump state"); } // Public API: create, maybe jump, catch-and-match, finally close. // See callWithNonLocalExit for below. /** Create a non-local exit point at the start of some scope. * Caller is responsible to catch, within the scope, {@link Jump Jumps} which may be directed * at this point, and to {@link #close() close the exit point} when it goes out of scope. *

Example code: *

     *  NonLocalExit exit = new NonLocalExit();
     *  try {
     *      callSomethingRecursiveWithAnEscapeHatch(exit);
     *      return somethingLocal;
     *  } catch (NonLocalExit.Jump t) {
     *      if (!exit.matches(t))
     *          // These are not the droids you're looking for.  Move along.
     *          throw t;
     *      return somethingElseLocal;
     *  } finally {
     *      exit.close();
     *  }
     * 
*

Note that this class can be subclassed to “box” a return value, * which would be delivered instead of somethingElseLocal * in the above example. */ public NonLocalExit() { // Mark this exit point as accessible (in this thread). if (!NOCHECK) initState(); // else null scope means "Do I feel lucky today?" } /** Make a non-local jump to the end of my scope. * Concretely, throw an exception to my associated * exception handler which matches me. * This is usually invoked at most once per exit point instance. */ public void jump() { // Make sure we are active in the correct thread. if (!NOCHECK) checkState(); // Use an internal throwable to transfer the control. Jump t = makeJump(); jump = t; // mark target as 'in-flight' with t throw t; // happy landings! } // Ugly multiple jump scenario, in pseudocode: // L: { try { L.jump(); } finally { L.jump(); } } // It's ugly, but it will work. /** Must be used in my associated catch clause to verify that * a passing exception is one this pertains to me. * If it returns true, then the caller should pass control * normally out of my associated scope. * If it returns false, the the caller must * rethrow the caught exception, because it is aimed at a different * scope (i.e., a different {@link NonLocalExit} instance). */ public boolean matches(Throwable t) { return (jump == t); } /** Make me go out of scope. Caller should do this in a * finally clause, or else error checking * may produce unhelpful results. */ public void close() { // Mark this exit point as dead (inaccessible even in this thread). if (!NOCHECK) this.scope = null; } } ////////////////////////////// // The rest of this file is really example code and can be removed. // Typical run: // % javac NonLocalExit.java && java NonLocalExitExample // Warming up... // Making timing run: // Time per iteration: 1.891 us class NonLocalExitExample { // Canonical usage: interface Callable { public R callWith(NonLocalExit exit, T x); } static R callWithNonLocalExit(Callable fn, T x) { NonLocalExit exit = new NonLocalExit(); try { return fn.callWith(exit, x); } catch (NonLocalExit.Jump t) { // Or, catch (Throwable t), even. if (!exit.matches(t)) // These are not the droids you're looking for. Move along. throw t; return null; } finally { exit.close(); } } // Test harness: public static long test(final int iterations, final int normalExits) { // Using this micro-benchmark, the cost of a non-local return appears to be about // ten times the cost of a regular return, with a lightly optimizing JIT. // For example, "java NonLocalExit 1000000 20" has been observed to report // a similar time to "java NonLocalExit 1000000 -30", and likewise for other // pairs where the second arguments add up to "-10". long t0 = System.nanoTime(); for (int i = 0; i < iterations; i++) { Callable fn = new Callable() { int normalExitsRemaining = normalExits; public Object callWith(NonLocalExit exit, Object x) { if (normalExitsRemaining != 0) --normalExitsRemaining; else exit.jump(); return null; } }; if (normalExits >= 0) { // call a bunch of times, and then do a NLE for (int j = normalExits; j >= 0; j--) callWithNonLocalExit(fn, null); } else { for (int j = normalExits; j < 0; j++) // call a bunch of times, and never do a NLE callWithNonLocalExit(fn, null); } } long t1 = System.nanoTime(); return t1 - t0; } public static void main(String[] av) { int arg0 = av.length <= 0 ? 1000*1000 : Integer.parseInt(av[0]); int arg1 = av.length <= 1 ? 0 : Integer.parseInt(av[1]); int arg2 = av.length <= 2 ? 0 : Integer.parseInt(av[2]); int iterations = arg0; int normalExits = arg1; int warmups = (arg2 == 0) ? iterations / 10 : arg2; if (NonLocalExit.NOCHECK == true) System.out.print("NOCHECK "); if (NonLocalExit.TRACE == true) System.out.print("TRACE "); //System.out.println("Props = "+System.getProperties()); System.out.println("Warming up..."); test(1000, 10); test(warmups, normalExits); System.out.println("Making timing run:"); double time = test(iterations, normalExits); System.out.println(String.format("Time per iteration: %.3f us", time / iterations / 1000)); } }