MutableCallSite.java revision 11477:65de62d768a4
1/*
2 * Copyright (c) 2008, 2013, 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
26package java.lang.invoke;
27
28import java.util.Objects;
29import java.util.concurrent.atomic.AtomicInteger;
30
31/**
32 * A {@code MutableCallSite} is a {@link CallSite} whose target variable
33 * behaves like an ordinary field.
34 * An {@code invokedynamic} instruction linked to a {@code MutableCallSite} delegates
35 * all calls to the site's current target.
36 * The {@linkplain CallSite#dynamicInvoker dynamic invoker} of a mutable call site
37 * also delegates each call to the site's current target.
38 * <p>
39 * Here is an example of a mutable call site which introduces a
40 * state variable into a method handle chain.
41 * <!-- JavaDocExamplesTest.testMutableCallSite -->
42 * <blockquote><pre>{@code
43MutableCallSite name = new MutableCallSite(MethodType.methodType(String.class));
44MethodHandle MH_name = name.dynamicInvoker();
45MethodType MT_str1 = MethodType.methodType(String.class);
46MethodHandle MH_upcase = MethodHandles.lookup()
47    .findVirtual(String.class, "toUpperCase", MT_str1);
48MethodHandle worker1 = MethodHandles.filterReturnValue(MH_name, MH_upcase);
49name.setTarget(MethodHandles.constant(String.class, "Rocky"));
50assertEquals("ROCKY", (String) worker1.invokeExact());
51name.setTarget(MethodHandles.constant(String.class, "Fred"));
52assertEquals("FRED", (String) worker1.invokeExact());
53// (mutation can be continued indefinitely)
54 * }</pre></blockquote>
55 * <p>
56 * The same call site may be used in several places at once.
57 * <blockquote><pre>{@code
58MethodType MT_str2 = MethodType.methodType(String.class, String.class);
59MethodHandle MH_cat = lookup().findVirtual(String.class,
60  "concat", methodType(String.class, String.class));
61MethodHandle MH_dear = MethodHandles.insertArguments(MH_cat, 1, ", dear?");
62MethodHandle worker2 = MethodHandles.filterReturnValue(MH_name, MH_dear);
63assertEquals("Fred, dear?", (String) worker2.invokeExact());
64name.setTarget(MethodHandles.constant(String.class, "Wilma"));
65assertEquals("WILMA", (String) worker1.invokeExact());
66assertEquals("Wilma, dear?", (String) worker2.invokeExact());
67 * }</pre></blockquote>
68 * <p>
69 * <em>Non-synchronization of target values:</em>
70 * A write to a mutable call site's target does not force other threads
71 * to become aware of the updated value.  Threads which do not perform
72 * suitable synchronization actions relative to the updated call site
73 * may cache the old target value and delay their use of the new target
74 * value indefinitely.
75 * (This is a normal consequence of the Java Memory Model as applied
76 * to object fields.)
77 * <p>
78 * The {@link #syncAll syncAll} operation provides a way to force threads
79 * to accept a new target value, even if there is no other synchronization.
80 * <p>
81 * For target values which will be frequently updated, consider using
82 * a {@linkplain VolatileCallSite volatile call site} instead.
83 * @author John Rose, JSR 292 EG
84 */
85public class MutableCallSite extends CallSite {
86    /**
87     * Creates a blank call site object with the given method type.
88     * The initial target is set to a method handle of the given type
89     * which will throw an {@link IllegalStateException} if called.
90     * <p>
91     * The type of the call site is permanently set to the given type.
92     * <p>
93     * Before this {@code CallSite} object is returned from a bootstrap method,
94     * or invoked in some other manner,
95     * it is usually provided with a more useful target method,
96     * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
97     * @param type the method type that this call site will have
98     * @throws NullPointerException if the proposed type is null
99     */
100    public MutableCallSite(MethodType type) {
101        super(type);
102    }
103
104    /**
105     * Creates a call site object with an initial target method handle.
106     * The type of the call site is permanently set to the initial target's type.
107     * @param target the method handle that will be the initial target of the call site
108     * @throws NullPointerException if the proposed target is null
109     */
110    public MutableCallSite(MethodHandle target) {
111        super(target);
112    }
113
114    /**
115     * Returns the target method of the call site, which behaves
116     * like a normal field of the {@code MutableCallSite}.
117     * <p>
118     * The interactions of {@code getTarget} with memory are the same
119     * as of a read from an ordinary variable, such as an array element or a
120     * non-volatile, non-final field.
121     * <p>
122     * In particular, the current thread may choose to reuse the result
123     * of a previous read of the target from memory, and may fail to see
124     * a recent update to the target by another thread.
125     *
126     * @return the linkage state of this call site, a method handle which can change over time
127     * @see #setTarget
128     */
129    @Override public final MethodHandle getTarget() {
130        return target;
131    }
132
133    /**
134     * Updates the target method of this call site, as a normal variable.
135     * The type of the new target must agree with the type of the old target.
136     * <p>
137     * The interactions with memory are the same
138     * as of a write to an ordinary variable, such as an array element or a
139     * non-volatile, non-final field.
140     * <p>
141     * In particular, unrelated threads may fail to see the updated target
142     * until they perform a read from memory.
143     * Stronger guarantees can be created by putting appropriate operations
144     * into the bootstrap method and/or the target methods used
145     * at any given call site.
146     *
147     * @param newTarget the new target
148     * @throws NullPointerException if the proposed new target is null
149     * @throws WrongMethodTypeException if the proposed new target
150     *         has a method type that differs from the previous target
151     * @see #getTarget
152     */
153    @Override public void setTarget(MethodHandle newTarget) {
154        checkTargetChange(this.target, newTarget);
155        setTargetNormal(newTarget);
156    }
157
158    /**
159     * {@inheritDoc}
160     */
161    @Override
162    public final MethodHandle dynamicInvoker() {
163        return makeDynamicInvoker();
164    }
165
166    /**
167     * Performs a synchronization operation on each call site in the given array,
168     * forcing all other threads to throw away any cached values previously
169     * loaded from the target of any of the call sites.
170     * <p>
171     * This operation does not reverse any calls that have already started
172     * on an old target value.
173     * (Java supports {@linkplain java.lang.Object#wait() forward time travel} only.)
174     * <p>
175     * The overall effect is to force all future readers of each call site's target
176     * to accept the most recently stored value.
177     * ("Most recently" is reckoned relative to the {@code syncAll} itself.)
178     * Conversely, the {@code syncAll} call may block until all readers have
179     * (somehow) decached all previous versions of each call site's target.
180     * <p>
181     * To avoid race conditions, calls to {@code setTarget} and {@code syncAll}
182     * should generally be performed under some sort of mutual exclusion.
183     * Note that reader threads may observe an updated target as early
184     * as the {@code setTarget} call that install the value
185     * (and before the {@code syncAll} that confirms the value).
186     * On the other hand, reader threads may observe previous versions of
187     * the target until the {@code syncAll} call returns
188     * (and after the {@code setTarget} that attempts to convey the updated version).
189     * <p>
190     * This operation is likely to be expensive and should be used sparingly.
191     * If possible, it should be buffered for batch processing on sets of call sites.
192     * <p>
193     * If {@code sites} contains a null element,
194     * a {@code NullPointerException} will be raised.
195     * In this case, some non-null elements in the array may be
196     * processed before the method returns abnormally.
197     * Which elements these are (if any) is implementation-dependent.
198     *
199     * <h1>Java Memory Model details</h1>
200     * In terms of the Java Memory Model, this operation performs a synchronization
201     * action which is comparable in effect to the writing of a volatile variable
202     * by the current thread, and an eventual volatile read by every other thread
203     * that may access one of the affected call sites.
204     * <p>
205     * The following effects are apparent, for each individual call site {@code S}:
206     * <ul>
207     * <li>A new volatile variable {@code V} is created, and written by the current thread.
208     *     As defined by the JMM, this write is a global synchronization event.
209     * <li>As is normal with thread-local ordering of write events,
210     *     every action already performed by the current thread is
211     *     taken to happen before the volatile write to {@code V}.
212     *     (In some implementations, this means that the current thread
213     *     performs a global release operation.)
214     * <li>Specifically, the write to the current target of {@code S} is
215     *     taken to happen before the volatile write to {@code V}.
216     * <li>The volatile write to {@code V} is placed
217     *     (in an implementation specific manner)
218     *     in the global synchronization order.
219     * <li>Consider an arbitrary thread {@code T} (other than the current thread).
220     *     If {@code T} executes a synchronization action {@code A}
221     *     after the volatile write to {@code V} (in the global synchronization order),
222     *     it is therefore required to see either the current target
223     *     of {@code S}, or a later write to that target,
224     *     if it executes a read on the target of {@code S}.
225     *     (This constraint is called "synchronization-order consistency".)
226     * <li>The JMM specifically allows optimizing compilers to elide
227     *     reads or writes of variables that are known to be useless.
228     *     Such elided reads and writes have no effect on the happens-before
229     *     relation.  Regardless of this fact, the volatile {@code V}
230     *     will not be elided, even though its written value is
231     *     indeterminate and its read value is not used.
232     * </ul>
233     * Because of the last point, the implementation behaves as if a
234     * volatile read of {@code V} were performed by {@code T}
235     * immediately after its action {@code A}.  In the local ordering
236     * of actions in {@code T}, this read happens before any future
237     * read of the target of {@code S}.  It is as if the
238     * implementation arbitrarily picked a read of {@code S}'s target
239     * by {@code T}, and forced a read of {@code V} to precede it,
240     * thereby ensuring communication of the new target value.
241     * <p>
242     * As long as the constraints of the Java Memory Model are obeyed,
243     * implementations may delay the completion of a {@code syncAll}
244     * operation while other threads ({@code T} above) continue to
245     * use previous values of {@code S}'s target.
246     * However, implementations are (as always) encouraged to avoid
247     * livelock, and to eventually require all threads to take account
248     * of the updated target.
249     *
250     * <p style="font-size:smaller;">
251     * <em>Discussion:</em>
252     * For performance reasons, {@code syncAll} is not a virtual method
253     * on a single call site, but rather applies to a set of call sites.
254     * Some implementations may incur a large fixed overhead cost
255     * for processing one or more synchronization operations,
256     * but a small incremental cost for each additional call site.
257     * In any case, this operation is likely to be costly, since
258     * other threads may have to be somehow interrupted
259     * in order to make them notice the updated target value.
260     * However, it may be observed that a single call to synchronize
261     * several sites has the same formal effect as many calls,
262     * each on just one of the sites.
263     *
264     * <p style="font-size:smaller;">
265     * <em>Implementation Note:</em>
266     * Simple implementations of {@code MutableCallSite} may use
267     * a volatile variable for the target of a mutable call site.
268     * In such an implementation, the {@code syncAll} method can be a no-op,
269     * and yet it will conform to the JMM behavior documented above.
270     *
271     * @param sites an array of call sites to be synchronized
272     * @throws NullPointerException if the {@code sites} array reference is null
273     *                              or the array contains a null
274     */
275    public static void syncAll(MutableCallSite[] sites) {
276        if (sites.length == 0)  return;
277        STORE_BARRIER.lazySet(0);
278        for (MutableCallSite site : sites) {
279            Objects.requireNonNull(site); // trigger NPE on first null
280        }
281        // FIXME: NYI
282    }
283    private static final AtomicInteger STORE_BARRIER = new AtomicInteger();
284}
285