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