jdk/src/share/classes/java/dyn/SwitchPoint.java
changeset 8823 7cd28219a1e4
parent 8717 f75a1efb1412
parent 8822 8145ab9f5f86
child 8824 0762fa26f813
child 9033 a88f5656f05d
equal deleted inserted replaced
8717:f75a1efb1412 8823:7cd28219a1e4
     1 /*
       
     2  * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package java.dyn;
       
    27 
       
    28 /**
       
    29  * <p>
       
    30  * A {@code SwitchPoint} is an object which can publish state transitions to other threads.
       
    31  * A switch point is initially in the <em>valid</em> state, but may at any time be
       
    32  * changed to the <em>invalid</em> state.  Invalidation cannot be reversed.
       
    33  * A switch point can combine a <em>guarded pair</em> of method handles into a
       
    34  * <em>guarded delegator</em>.
       
    35  * The guarded delegator is a method handle which delegates to one of the old method handles.
       
    36  * The state of the switch point determines which of the two gets the delegation.
       
    37  * <p>
       
    38  * A single switch point may be used to control any number of method handles.
       
    39  * (Indirectly, therefore, it can control any number of call sites.)
       
    40  * This is done by using the single switch point as a factory for combining
       
    41  * any number of guarded method handle pairs into guarded delegators.
       
    42  * <p>
       
    43  * When a guarded delegator is created from a guarded pair, the pair
       
    44  * is wrapped in a new method handle {@code M},
       
    45  * which is permanently associated with the switch point that created it.
       
    46  * Each pair consists of a target {@code T} and a fallback {@code F}.
       
    47  * While the switch point is valid, invocations to {@code M} are delegated to {@code T}.
       
    48  * After it is invalidated, invocations are delegated to {@code F}.
       
    49  * <p>
       
    50  * Invalidation is global and immediate, as if the switch point contained a
       
    51  * volatile boolean variable consulted on every call to {@code M}.
       
    52  * The invalidation is also permanent, which means the switch point
       
    53  * can change state only once.
       
    54  * The switch point will always delegate to {@code F} after being invalidated.
       
    55  * At that point {@code guardWithTest} may ignore {@code T} and return {@code F}.
       
    56  * <p>
       
    57  * Here is an example of a switch point in action:
       
    58  * <blockquote><pre>
       
    59 MethodType MT_str2 = MethodType.methodType(String.class, String.class);
       
    60 MethodHandle MH_strcat = MethodHandles.lookup()
       
    61     .findVirtual(String.class, "concat", MT_str2);
       
    62 SwitchPoint spt = new SwitchPoint();
       
    63 // the following steps may be repeated to re-use the same switch point:
       
    64 MethodHandle worker1 = strcat;
       
    65 MethodHandle worker2 = MethodHandles.permuteArguments(strcat, MT_str2, 1, 0);
       
    66 MethodHandle worker = spt.guardWithTest(worker1, worker2);
       
    67 assertEquals("method", (String) worker.invokeExact("met", "hod"));
       
    68 SwitchPoint.invalidateAll(new SwitchPoint[]{ spt });
       
    69 assertEquals("hodmet", (String) worker.invokeExact("met", "hod"));
       
    70  * </pre></blockquote>
       
    71  * <p style="font-size:smaller;">
       
    72  * <em>Discussion:</em>
       
    73  * Switch points are useful without subclassing.  They may also be subclassed.
       
    74  * This may be useful in order to associate application-specific invalidation logic
       
    75  * with the switch point.
       
    76  * <p style="font-size:smaller;">
       
    77  * <em>Implementation Note:</em>
       
    78  * A switch point behaves as if implemented on top of {@link MutableCallSite},
       
    79  * approximately as follows:
       
    80  * <blockquote><pre>
       
    81 public class SwitchPoint {
       
    82   private static final MethodHandle
       
    83     K_true  = MethodHandles.constant(boolean.class, true),
       
    84     K_false = MethodHandles.constant(boolean.class, false);
       
    85   private final MutableCallSite mcs;
       
    86   private final MethodHandle mcsInvoker;
       
    87   public SwitchPoint() {
       
    88     this.mcs = new MutableCallSite(K_true);
       
    89     this.mcsInvoker = mcs.dynamicInvoker();
       
    90   }
       
    91   public MethodHandle guardWithTest(
       
    92                 MethodHandle target, MethodHandle fallback) {
       
    93     // Note:  mcsInvoker is of type ()boolean.
       
    94     // Target and fallback may take any arguments, but must have the same type.
       
    95     return MethodHandles.guardWithTest(this.mcsInvoker, target, fallback);
       
    96   }
       
    97   public static void invalidateAll(SwitchPoint[] spts) {
       
    98     List&lt;MutableCallSite&gt; mcss = new ArrayList&lt;&gt;();
       
    99     for (SwitchPoint spt : spts)  mcss.add(spt.mcs);
       
   100     for (MutableCallSite mcs : mcss)  mcs.setTarget(K_false);
       
   101     MutableCallSite.syncAll(mcss.toArray(new MutableCallSite[0]));
       
   102   }
       
   103 }
       
   104  * </pre></blockquote>
       
   105  * @author Remi Forax, JSR 292 EG
       
   106  */
       
   107 public class SwitchPoint {
       
   108     private static final MethodHandle
       
   109         K_true  = MethodHandles.constant(boolean.class, true),
       
   110         K_false = MethodHandles.constant(boolean.class, false);
       
   111 
       
   112     private final MutableCallSite mcs;
       
   113     private final MethodHandle mcsInvoker;
       
   114 
       
   115     /**
       
   116      * Creates a new switch point.
       
   117      */
       
   118     public SwitchPoint() {
       
   119         this.mcs = new MutableCallSite(K_true);
       
   120         this.mcsInvoker = mcs.dynamicInvoker();
       
   121     }
       
   122 
       
   123     /**
       
   124      * Returns a method handle which always delegates either to the target or the fallback.
       
   125      * The method handle will delegate to the target exactly as long as the switch point is valid.
       
   126      * After that, it will permanently delegate to the fallback.
       
   127      * <p>
       
   128      * The target and fallback must be of exactly the same method type,
       
   129      * and the resulting combined method handle will also be of this type.
       
   130      *
       
   131      * @param target the method handle selected by the switch point as long as it is valid
       
   132      * @param fallback the method handle selected by the switch point after it is invalidated
       
   133      * @return a combined method handle which always calls either the target or fallback
       
   134      * @throws NullPointerException if either argument is null
       
   135      * @see MethodHandles#guardWithTest
       
   136      */
       
   137     public MethodHandle guardWithTest(MethodHandle target, MethodHandle fallback) {
       
   138         if (mcs.getTarget() == K_false)
       
   139             return fallback;  // already invalid
       
   140         return MethodHandles.guardWithTest(mcsInvoker, target, fallback);
       
   141     }
       
   142 
       
   143     /**
       
   144      * Sets all of the given switch points into the invalid state.
       
   145      * After this call executes, no thread will observe any of the
       
   146      * switch points to be in a valid state.
       
   147      * <p>
       
   148      * This operation is likely to be expensive and should be used sparingly.
       
   149      * If possible, it should be buffered for batch processing on sets of switch points.
       
   150      * <p>
       
   151      * If {@code switchPoints} contains a null element,
       
   152      * a {@code NullPointerException} will be raised.
       
   153      * In this case, some non-null elements in the array may be
       
   154      * processed before the method returns abnormally.
       
   155      * Which elements these are (if any) is implementation-dependent.
       
   156      *
       
   157      * <p style="font-size:smaller;">
       
   158      * <em>Discussion:</em>
       
   159      * For performance reasons, {@code invalidateAll} is not a virtual method
       
   160      * on a single switch point, but rather applies to a set of switch points.
       
   161      * Some implementations may incur a large fixed overhead cost
       
   162      * for processing one or more invalidation operations,
       
   163      * but a small incremental cost for each additional invalidation.
       
   164      * In any case, this operation is likely to be costly, since
       
   165      * other threads may have to be somehow interrupted
       
   166      * in order to make them notice the updated switch point state.
       
   167      * However, it may be observed that a single call to invalidate
       
   168      * several switch points has the same formal effect as many calls,
       
   169      * each on just one of the switch points.
       
   170      *
       
   171      * <p style="font-size:smaller;">
       
   172      * <em>Implementation Note:</em>
       
   173      * Simple implementations of {@code SwitchPoint} may use
       
   174      * a private {@link MutableCallSite} to publish the state of a switch point.
       
   175      * In such an implementation, the {@code invalidateAll} method can
       
   176      * simply change the call site's target, and issue one call to
       
   177      * {@linkplain MutableCallSite#syncAll synchronize} all the
       
   178      * private call sites.
       
   179      *
       
   180      * @param switchPoints an array of call sites to be synchronized
       
   181      * @throws NullPointerException if the {@code switchPoints} array reference is null
       
   182      *                              or the array contains a null
       
   183      */
       
   184     public static void invalidateAll(SwitchPoint[] switchPoints) {
       
   185         if (switchPoints.length == 0)  return;
       
   186         MutableCallSite[] sites = new MutableCallSite[switchPoints.length];
       
   187         for (int i = 0; i < switchPoints.length; i++) {
       
   188             SwitchPoint spt = switchPoints[i];
       
   189             if (spt == null)  break;  // MSC.syncAll will trigger a NPE
       
   190             sites[i] = spt.mcs;
       
   191             spt.mcs.setTarget(K_false);
       
   192         }
       
   193         MutableCallSite.syncAll(sites);
       
   194     }
       
   195 }