Path: blob/master/src/jdk.dynalink/share/classes/jdk/dynalink/support/ChainedCallSite.java
41161 views
/*1* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file, and Oracle licenses the original version of this file under the BSD30* license:31*/32/*33Copyright 2009-2013 Attila Szegedi3435Redistribution and use in source and binary forms, with or without36modification, are permitted provided that the following conditions are37met:38* Redistributions of source code must retain the above copyright39notice, this list of conditions and the following disclaimer.40* Redistributions in binary form must reproduce the above copyright41notice, this list of conditions and the following disclaimer in the42documentation and/or other materials provided with the distribution.43* Neither the name of the copyright holder nor the names of44contributors may be used to endorse or promote products derived from45this software without specific prior written permission.4647THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS48IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED49TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A50PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER51BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR52CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF53SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR54BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,55WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR56OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF57ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.58*/5960package jdk.dynalink.support;6162import java.lang.invoke.MethodHandle;63import java.lang.invoke.MethodHandles;64import java.util.Arrays;65import java.util.LinkedList;66import jdk.dynalink.CallSiteDescriptor;67import jdk.dynalink.linker.GuardedInvocation;68import jdk.dynalink.linker.support.Lookup;6970/**71* A relinkable call site that implements a polymorphic inline caching strategy.72* It remembers up to 8 {@link GuardedInvocation}s it was linked with, and on73* each relink request builds a cascading chain of method handles of one74* invocation falling back to the next one. The number of remembered invocations75* can be customized by overriding {@link #getMaxChainLength()} in a subclass.76* When this call site is relinked with a new invocation and the length of the77* chain is already at the maximum, it will throw away the oldest invocation.78* Invocations with invalidated switch points and ones for which their79* invalidating exception triggered are removed eagerly from the chain. The80* invocations are never reordered; the most recently linked method handle is81* always at the start of the chain and the least recently linked at its end.82* The call site can be safely relinked on more than one thread concurrently.83* Race conditions in linking are resolved by throwing away the84* {@link GuardedInvocation} produced on the losing thread without incorporating85* it into the chain, so it can lead to repeated linking for the same arguments.86*/87public class ChainedCallSite extends AbstractRelinkableCallSite {88private static final MethodHandle PRUNE_CATCHES;89private static final MethodHandle PRUNE_SWITCHPOINTS;90static {91final MethodHandle PRUNE = Lookup.findOwnSpecial(MethodHandles.lookup(), "prune", MethodHandle.class,92MethodHandle.class, boolean.class);93PRUNE_CATCHES = MethodHandles.insertArguments(PRUNE, 2, true);94PRUNE_SWITCHPOINTS = MethodHandles.insertArguments(PRUNE, 2, false);95}9697/**98* Contains the invocations currently linked into this call site's target. They are used when we are99* relinking to rebuild the guardWithTest chain. Valid values for this field are: {@code null} if there's100* no linked invocations, or an instance of {@link GuardedInvocation} if there is exactly one previous101* invocation, or an instance of {@code GuardedInvocation[]} if there is more than one previous102* invocation.103*/104private Object invocations;105106/**107* Creates a new chained call site.108* @param descriptor the descriptor for the call site.109*/110public ChainedCallSite(final CallSiteDescriptor descriptor) {111super(descriptor);112}113114/**115* The maximum number of method handles in the chain. Defaults to 8. You can116* override it in a subclass if you need to change the value.117* @return the maximum number of method handles in the chain. The return118* value is checked, and if your override returns a value less than 1, a119* {@link RuntimeException} will be thrown.120*/121protected int getMaxChainLength() {122return 8;123}124125@Override126public void relink(final GuardedInvocation guardedInvocation, final MethodHandle relinkAndInvoke) {127relinkInternal(guardedInvocation, relinkAndInvoke, false, false);128}129130@Override131public void resetAndRelink(final GuardedInvocation guardedInvocation, final MethodHandle relinkAndInvoke) {132relinkInternal(guardedInvocation, relinkAndInvoke, true, false);133}134135private MethodHandle relinkInternal(final GuardedInvocation invocation, final MethodHandle relink, final boolean reset, final boolean removeCatches) {136final Object currentInvocations = invocations;137final LinkedList<GuardedInvocation> newInvocations;138if (currentInvocations == null || reset) {139newInvocations = new LinkedList<>();140} else if (currentInvocations instanceof GuardedInvocation) {141newInvocations = new LinkedList<>();142newInvocations.add((GuardedInvocation)currentInvocations);143} else if (currentInvocations instanceof GuardedInvocation[]) {144newInvocations = new LinkedList<>(Arrays.asList(((GuardedInvocation[])currentInvocations)));145} else {146throw new AssertionError();147}148149// First, prune the chain of invalidated switchpoints, we always do this150// We also remove any catches if the remove catches flag is set151newInvocations.removeIf(inv ->152inv.hasBeenInvalidated() || (removeCatches && inv.getException() != null)153);154155// prune() is allowed to invoke this method with invocation == null meaning we're just pruning the chain and not156// adding any new invocations to it.157if(invocation != null) {158// Remove oldest entry if we're at max length159if(newInvocations.size() == checkMaxChainLength(getMaxChainLength())) {160newInvocations.removeFirst();161}162newInvocations.addLast(invocation);163}164165// prune-and-invoke is used as the fallback for invalidated switchpoints. If a switchpoint gets invalidated, we166// rebuild the chain and get rid of all invalidated switchpoints instead of letting them linger.167final MethodHandle pruneAndInvokeSwitchPoints = makePruneAndInvokeMethod(relink, PRUNE_SWITCHPOINTS);168final MethodHandle pruneAndInvokeCatches = makePruneAndInvokeMethod(relink, PRUNE_CATCHES);169170// Fold the new chain171MethodHandle target = relink;172for(final GuardedInvocation inv: newInvocations) {173target = inv.compose(target, pruneAndInvokeSwitchPoints, pruneAndInvokeCatches);174}175176switch (newInvocations.size()) {177case 0:178invocations = null;179break;180case 1:181invocations = newInvocations.getFirst();182break;183default:184invocations = newInvocations.toArray(new GuardedInvocation[0]);185}186setTarget(target);187return target;188}189190private static int checkMaxChainLength(final int maxChainLength) {191if (maxChainLength > 0) {192return maxChainLength;193}194throw new RuntimeException("getMaxChainLength() returned a non-positive value");195196}197/**198* Creates a method that rebuilds our call chain, pruning it of any invalidated switchpoints, and then invokes that199* chain.200* @param relinkAndInvoke the ultimate fallback for the chain passed from the dynamic linker.201* @return a method handle for prune-and-invoke202*/203private MethodHandle makePruneAndInvokeMethod(final MethodHandle relinkAndInvoke, final MethodHandle prune) {204// Bind prune to (this, relink)205final MethodHandle boundPrune = MethodHandles.insertArguments(prune, 0, this, relinkAndInvoke);206// Make it ignore all incoming arguments207final MethodHandle ignoreArgsPrune = MethodHandles.dropArguments(boundPrune, 0, type().parameterList());208// Invoke prune, then invoke the call site target with original arguments209return MethodHandles.foldArguments(MethodHandles.exactInvoker(type()), ignoreArgsPrune);210}211212@SuppressWarnings("unused")213private MethodHandle prune(final MethodHandle relink, final boolean catches) {214return relinkInternal(null, relink, false, catches);215}216}217218219