提交 d7393144 编写于 作者: J jrose

7012650: implement JSR 292 EG adjustments through January 2010

Summary: misc. EG changes and polishes (excluding 7013417)
Reviewed-by: twisti
上级 f39741d7
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -78,7 +78,7 @@ static {
}
private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String name, MethodType type) {
// ignore caller and name, but match the type:
return new ConstantCallSite(MethodHandles.collectArguments(printArgs, type));
return new ConstantCallSite(printArgs.asType(type));
}
</pre></blockquote>
* @author John Rose, JSR 292 EG
......@@ -86,6 +86,7 @@ private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String nam
abstract
public class CallSite {
private static final Access IMPL_TOKEN = Access.getToken();
static { MethodHandleImpl.initStatics(); }
// Fields used only by the JVM. Do not use or change.
private MemberName vmmethod; // supplied by the JVM (ref. to calling method)
......@@ -125,8 +126,8 @@ public class CallSite {
}
/**
* Report the type of this call site's target.
* Although targets may change, the call site's type can never change.
* Returns the type of this call site's target.
* Although targets may change, any call site's type is permanent, and can never change to an unequal type.
* The {@code setTarget} method enforces this invariant by refusing any new target that does
* not have the previous target's type.
* @return the type of the current target, which is also the type of any future target
......@@ -154,73 +155,40 @@ public class CallSite {
}
/**
* Report the current linkage state of the call site, a value which may change over time.
* <p>
* If a {@code CallSite} object is returned
* from the bootstrap method of the {@code invokedynamic} instruction,
* the {@code CallSite} is permanently bound to that instruction.
* When the {@code invokedynamic} instruction is executed, the target method
* of its associated call site object is invoked directly.
* It is as if the instruction calls {@code getTarget} and then
* calls {@link MethodHandle#invokeExact invokeExact} on the result.
* <p>
* Unless specified differently by a subclass,
* the interactions of {@code getTarget} with memory are the same
* as of a read from an ordinary variable, such as an array element or a
* non-volatile, non-final field.
* <p>
* In particular, the current thread may choose to reuse the result
* of a previous read of the target from memory, and may fail to see
* a recent update to the target by another thread.
* <p>
* In a {@linkplain ConstantCallSite constant call site}, the {@code getTarget} method behaves
* like a read from a {@code final} field of the {@code CallSite}.
* <p>
* In a {@linkplain VolatileCallSite volatile call site}, the {@code getTarget} method behaves
* like a read from a {@code volatile} field of the {@code CallSite}.
* <p>
* This method may not be overridden by application code.
* Returns the target method of the call site, according to the
* behavior defined by this call site's specific class.
* The immediate subclasses of {@code CallSite} document the
* class-specific behaviors of this method.
*
* @return the current linkage state of the call site, its target method handle
* @see ConstantCallSite
* @see VolatileCallSite
* @see #setTarget
* @see ConstantCallSite#getTarget
* @see MutableCallSite#getTarget
* @see VolatileCallSite#getTarget
*/
public final MethodHandle getTarget() {
return getTarget0();
}
/**
* Privileged implementations can override this to force final or volatile semantics on getTarget.
*/
/*package-private*/
MethodHandle getTarget0() {
return target;
}
public abstract MethodHandle getTarget();
/**
* Set the target method of this call site.
* Updates the target method of this call site, according to the
* behavior defined by this call site's specific class.
* The immediate subclasses of {@code CallSite} document the
* class-specific behaviors of this method.
* <p>
* Unless a subclass of CallSite documents otherwise,
* the interactions of {@code setTarget} with memory are the same
* as of a write to an ordinary variable, such as an array element or a
* non-volatile, non-final field.
* <p>
* In particular, unrelated threads may fail to see the updated target
* until they perform a read from memory.
* Stronger guarantees can be created by putting appropriate operations
* into the bootstrap method and/or the target methods used
* at any given call site.
* The type of the new target must be {@linkplain MethodType#equals equal to}
* the type of the old target.
*
* @param newTarget the new target
* @throws NullPointerException if the proposed new target is null
* @throws WrongMethodTypeException if the proposed new target
* has a method type that differs from the previous target
* @throws UnsupportedOperationException if the call site is
* in fact a {@link ConstantCallSite}
* @see CallSite#getTarget
* @see ConstantCallSite#setTarget
* @see MutableCallSite#setTarget
* @see VolatileCallSite#setTarget
*/
public void setTarget(MethodHandle newTarget) {
checkTargetChange(this.target, newTarget);
setTargetNormal(newTarget);
}
public abstract void setTarget(MethodHandle newTarget);
void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
MethodType oldType = oldTarget.type();
......@@ -236,25 +204,25 @@ public class CallSite {
/**
* Produce a method handle equivalent to an invokedynamic instruction
* which has been linked to this call site.
* <p>If this call site is a {@linkplain ConstantCallSite constant call site},
* this method simply returns the call site's target, since that will never change.
* <p>Otherwise, this method is equivalent to the following code:
* <p><blockquote><pre>
* <p>
* This method is equivalent to the following code:
* <blockquote><pre>
* MethodHandle getTarget, invoker, result;
* getTarget = MethodHandles.lookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
* getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
* invoker = MethodHandles.exactInvoker(this.type());
* result = MethodHandles.foldArguments(invoker, getTarget)
* </pre></blockquote>
*
* @return a method handle which always invokes this call site's current target
*/
public final MethodHandle dynamicInvoker() {
if (this instanceof ConstantCallSite) {
return getTarget0(); // will not change dynamically
}
public abstract MethodHandle dynamicInvoker();
/*non-public*/ MethodHandle makeDynamicInvoker() {
MethodHandle getTarget = MethodHandleImpl.bindReceiver(IMPL_TOKEN, GET_TARGET, this);
MethodHandle invoker = MethodHandles.exactInvoker(this.type());
return MethodHandles.foldArguments(invoker, getTarget);
}
private static final MethodHandle GET_TARGET;
static {
try {
......
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -31,10 +31,14 @@ import java.util.concurrent.atomic.AtomicReference;
import java.lang.reflect.UndeclaredThrowableException;
/**
* Lazily associate a computed value with (potentially) every class.
* Lazily associate a computed value with (potentially) every type.
* For example, if a dynamic language needs to construct a message dispatch
* table for each class encountered at a message send call site,
* it can use a {@code ClassValue} to cache information needed to
* perform the message send quickly, for each class encountered.
* @author John Rose, JSR 292 EG
*/
public class ClassValue<T> {
public abstract class ClassValue<T> {
/**
* Compute the given class's derived value for this {@code ClassValue}.
* <p>
......@@ -45,61 +49,41 @@ public class ClassValue<T> {
* but it may be invoked again if there has been a call to
* {@link #remove remove}.
* <p>
* If there is no override from a subclass, this method returns
* the result of applying the {@code ClassValue}'s {@code computeValue}
* method handle, which was supplied at construction time.
* If this method throws an exception, the corresponding call to {@code get}
* will terminate abnormally with that exception, and no class value will be recorded.
*
* @param type the type whose class value must be computed
* @return the newly computed value associated with this {@code ClassValue}, for the given class or interface
* @throws UndeclaredThrowableException if the {@code computeValue} method handle invocation throws something other than a {@code RuntimeException} or {@code Error}
* @throws UnsupportedOperationException if the {@code computeValue} method handle is null (subclasses must override)
* @see #get
* @see #remove
*/
protected T computeValue(Class<?> type) {
if (computeValue == null)
return null;
try {
return (T) (Object) computeValue.invokeGeneric(type);
} catch (Throwable ex) {
if (ex instanceof Error) throw (Error) ex;
if (ex instanceof RuntimeException) throw (RuntimeException) ex;
throw new UndeclaredThrowableException(ex);
}
}
private final MethodHandle computeValue;
/**
* Creates a new class value.
* Subclasses which use this constructor must override
* the {@link #computeValue computeValue} method,
* since the default {@code computeValue} method requires a method handle,
* which this constructor does not provide.
*/
protected ClassValue() {
this.computeValue = null;
}
/**
* Creates a new class value, whose {@link #computeValue computeValue} method
* will return the result of {@code computeValue.invokeGeneric(type)}.
* @throws NullPointerException if the method handle parameter is null
*/
public ClassValue(MethodHandle computeValue) {
computeValue.getClass(); // trigger NPE if null
this.computeValue = computeValue;
}
protected abstract T computeValue(Class<?> type);
/**
* Returns the value for the given class.
* If no value has yet been computed, it is obtained by
* by an invocation of the {@link #computeValue computeValue} method.
* an invocation of the {@link #computeValue computeValue} method.
* <p>
* The actual installation of the value on the class
* is performed atomically.
* At that point, if racing threads have
* At that point, if several racing threads have
* computed values, one is chosen, and returned to
* all the racing threads.
* <p>
* The {@code type} parameter is typically a class, but it may be any type,
* such as an interface, a primitive type (like {@code int.class}), or {@code void.class}.
* <p>
* In the absence of {@code remove} calls, a class value has a simple
* state diagram: uninitialized and initialized.
* When {@code remove} calls are made,
* the rules for value observation are more complex.
* See the documentation for {@link #remove remove} for more information.
*
* @param type the type whose class value must be computed or retrieved
* @return the current value associated with this {@code ClassValue}, for the given class or interface
* @throws NullPointerException if the argument is null
* @see #remove
* @see #computeValue
*/
public T get(Class<?> type) {
ClassValueMap map = getMap(type);
......@@ -119,12 +103,51 @@ public class ClassValue<T> {
* This may result in an additional invocation of the
* {@code computeValue computeValue} method for the given class.
* <p>
* If racing threads perform a combination of {@code get} and {@code remove} calls,
* the calls are serialized.
* A value produced by a call to {@code computeValue} will be discarded, if
* the corresponding {@code get} call was followed by a {@code remove} call
* before the {@code computeValue} could complete.
* In such a case, the {@code get} call will re-invoke {@code computeValue}.
* In order to explain the interaction between {@code get} and {@code remove} calls,
* we must model the state transitions of a class value to take into account
* the alternation between uninitialized and initialized states.
* To do this, number these states sequentially from zero, and note that
* uninitialized (or removed) states are numbered with even numbers,
* while initialized (or re-initialized) states have odd numbers.
* <p>
* When a thread {@code T} removes a class value in state {@code 2N},
* nothing happens, since the class value is already uninitialized.
* Otherwise, the state is advanced atomically to {@code 2N+1}.
* <p>
* When a thread {@code T} queries a class value in state {@code 2N},
* the thread first attempts to initialize the class value to state {@code 2N+1}
* by invoking {@code computeValue} and installing the resulting value.
* <p>
* When {@code T} attempts to install the newly computed value,
* if the state is still at {@code 2N}, the class value will be initialized
* with the computed value, advancing it to state {@code 2N+1}.
* <p>
* Otherwise, whether the new state is even or odd,
* {@code T} will discard the newly computed value
* and retry the {@code get} operation.
* <p>
* Discarding and retrying is an important proviso,
* since otherwise {@code T} could potentially install
* a disastrously stale value. For example:
* <ul>
* <li>{@code T} calls {@code CV.get(C)} and sees state {@code 2N}
* <li>{@code T} quickly computes a time-dependent value {@code V0} and gets ready to install it
* <li>{@code T} is hit by an unlucky paging or scheduling event, and goes to sleep for a long time
* <li>...meanwhile, {@code T2} also calls {@code CV.get(C)} and sees state {@code 2N}
* <li>{@code T2} quickly computes a similar time-dependent value {@code V1} and installs it on {@code CV.get(C)}
* <li>{@code T2} (or a third thread) then calls {@code CV.remove(C)}, undoing {@code T2}'s work
* <li> the previous actions of {@code T2} are repeated several times
* <li> also, the relevant computed values change over time: {@code V1}, {@code V2}, ...
* <li>...meanwhile, {@code T} wakes up and attempts to install {@code V0}; <em>this must fail</em>
* </ul>
* We can assume in the above scenario that {@code CV.computeValue} uses locks to properly
* observe the time-dependent states as it computes {@code V1}, etc.
* This does not remove the threat of a stale value, since there is a window of time
* between the return of {@code computeValue} in {@code T} and the installation
* of the the new value. No user synchronization is possible during this time.
*
* @param type the type whose class value must be removed
* @throws NullPointerException if the argument is null
*/
public void remove(Class<?> type) {
ClassValueMap map = getMap(type);
......@@ -137,9 +160,9 @@ public class ClassValue<T> {
/// Implementation...
/** The hash code for this type is based on the identity of the object,
* and is well-dispersed for power-of-two tables.
*/
// The hash code for this type is based on the identity of the object,
// and is well-dispersed for power-of-two tables.
/** @deprecated This override, which is implementation-specific, will be removed for PFD. */
public final int hashCode() { return hashCode; }
private final int hashCode = HASH_CODES.getAndAdd(0x61c88647);
private static final AtomicInteger HASH_CODES = new AtomicInteger();
......
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -32,16 +32,46 @@ package java.dyn;
* @author John Rose, JSR 292 EG
*/
public class ConstantCallSite extends CallSite {
/** Create a call site with a permanent target.
/**
* Creates a call site with a permanent target.
* @param target the target to be permanently associated with this call site
* @throws NullPointerException if the proposed target is null
*/
public ConstantCallSite(MethodHandle target) {
super(target);
}
/**
* Returns the target method of the call site, which behaves
* like a {@code final} field of the {@code ConstantCallSite}.
* That is, the the target is always the original value passed
* to the constructor call which created this instance.
*
* @return the immutable linkage state of this call site, a constant method handle
* @throws UnsupportedOperationException because this kind of call site cannot change its target
*/
@Override public final MethodHandle getTarget() {
return target;
}
/**
* Throw an {@link UnsupportedOperationException}, because this kind of call site cannot change its target.
* Always throws an {@link UnsupportedOperationException}.
* This kind of call site cannot change its target.
* @param ignore a new target proposed for the call site, which is ignored
* @throws UnsupportedOperationException because this kind of call site cannot change its target
*/
@Override public final void setTarget(MethodHandle ignore) {
throw new UnsupportedOperationException("ConstantCallSite");
}
/**
* Returns this call site's permanent target.
* Since that target will never change, this is a correct implementation
* of {@link CallSite#dynamicInvoker CallSite.dynamicInvoker}.
* @return the immutable linkage state of this call site, a constant method handle
*/
@Override
public final MethodHandle dynamicInvoker() {
return getTarget();
}
}
......@@ -31,8 +31,8 @@ package java.dyn;
* {@linkplain BootstrapMethod bootstrap method},
* or the bootstrap method has
* failed to provide a
* {@linkplain CallSite} call site with a non-null {@linkplain MethodHandle target}
* of the correct {@linkplain MethodType method type}.
* {@linkplain CallSite call site} with a {@linkplain CallSite#getTarget target}
* of the correct {@linkplain MethodHandle#type method type}.
*
* @author John Rose, JSR 292 EG
* @since 1.7
......
......@@ -101,8 +101,9 @@ public class Linkage {
/**
* <em>METHOD WILL BE REMOVED FOR PFD:</em>
* Invalidate all <code>invokedynamic</code> call sites everywhere.
* @deprecated Use {@linkplain CallSite#setTarget call site target setting}
* and {@link VolatileCallSite#invalidateAll call site invalidation} instead.
* @deprecated Use {@linkplain MutableCallSite#setTarget call site target setting},
* {@link MutableCallSite#syncAll call site update pushing},
* and {@link SwitchPoint#guardWithTest target switching} instead.
*/
public static
Object invalidateAll() {
......@@ -113,8 +114,9 @@ public class Linkage {
* <em>METHOD WILL BE REMOVED FOR PFD:</em>
* Invalidate all {@code invokedynamic} call sites in the bytecodes
* of any methods of the given class.
* @deprecated Use {@linkplain CallSite#setTarget call site target setting}
* and {@link VolatileCallSite#invalidateAll call site invalidation} instead.
* @deprecated Use {@linkplain MutableCallSite#setTarget call site target setting},
* {@link MutableCallSite#syncAll call site update pushing},
* and {@link SwitchPoint#guardWithTest target switching} instead.
*/
public static
Object invalidateCallerClass(Class<?> callerClass) {
......
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -73,7 +73,7 @@ assertEquals("Wilma, dear?", (String) worker2.invokeExact());
* (This is a normal consequence of the Java Memory Model as applied
* to object fields.)
* <p>
* The {@link #sync sync} operation provides a way to force threads
* The {@link #syncAll syncAll} operation provides a way to force threads
* to accept a new target value, even if there is no other synchronization.
* <p>
* For target values which will be frequently updated, consider using
......@@ -82,13 +82,17 @@ assertEquals("Wilma, dear?", (String) worker2.invokeExact());
*/
public class MutableCallSite extends CallSite {
/**
* Make a blank call site object with the given method type.
* An initial target method is supplied which will throw
* an {@link IllegalStateException} if called.
* Creates a blank call site object with the given method type.
* The initial target is set to a method handle of the given type
* which will throw an {@link IllegalStateException} if called.
* <p>
* The type of the call site is permanently set to the given type.
* <p>
* Before this {@code CallSite} object is returned from a bootstrap method,
* or invoked in some other manner,
* it is usually provided with a more useful target method,
* via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
* @param type the method type that this call site will have
* @throws NullPointerException if the proposed type is null
*/
public MutableCallSite(MethodType type) {
......@@ -96,8 +100,9 @@ public class MutableCallSite extends CallSite {
}
/**
* Make a blank call site object, possibly equipped with an initial target method handle.
* @param target the method handle which will be the initial target of the call site
* Creates a call site object with an initial target method handle.
* The type of the call site is permanently set to the initial target's type.
* @param target the method handle that will be the initial target of the call site
* @throws NullPointerException if the proposed target is null
*/
public MutableCallSite(MethodHandle target) {
......@@ -105,7 +110,59 @@ public class MutableCallSite extends CallSite {
}
/**
* Perform a synchronization operation on each call site in the given array,
* Returns the target method of the call site, which behaves
* like a normal field of the {@code MutableCallSite}.
* <p>
* The interactions of {@code getTarget} with memory are the same
* as of a read from an ordinary variable, such as an array element or a
* non-volatile, non-final field.
* <p>
* In particular, the current thread may choose to reuse the result
* of a previous read of the target from memory, and may fail to see
* a recent update to the target by another thread.
*
* @return the linkage state of this call site, a method handle which can change over time
* @see #setTarget
*/
@Override public final MethodHandle getTarget() {
return target;
}
/**
* Updates the target method of this call site, as a normal variable.
* The type of the new target must agree with the type of the old target.
* <p>
* The interactions with memory are the same
* as of a write to an ordinary variable, such as an array element or a
* non-volatile, non-final field.
* <p>
* In particular, unrelated threads may fail to see the updated target
* until they perform a read from memory.
* Stronger guarantees can be created by putting appropriate operations
* into the bootstrap method and/or the target methods used
* at any given call site.
*
* @param newTarget the new target
* @throws NullPointerException if the proposed new target is null
* @throws WrongMethodTypeException if the proposed new target
* has a method type that differs from the previous target
* @see #getTarget
*/
@Override public void setTarget(MethodHandle newTarget) {
checkTargetChange(this.target, newTarget);
setTargetNormal(newTarget);
}
/**
* {@inheritDoc}
*/
@Override
public final MethodHandle dynamicInvoker() {
return makeDynamicInvoker();
}
/**
* Performs a synchronization operation on each call site in the given array,
* forcing all other threads to throw away any cached values previously
* loaded from the target of any of the call sites.
* <p>
......@@ -115,19 +172,29 @@ public class MutableCallSite extends CallSite {
* <p>
* The overall effect is to force all future readers of each call site's target
* to accept the most recently stored value.
* ("Most recently" is reckoned relative to the {@code sync} itself.)
* Conversely, the {@code sync} call may block until all readers have
* ("Most recently" is reckoned relative to the {@code syncAll} itself.)
* Conversely, the {@code syncAll} call may block until all readers have
* (somehow) decached all previous versions of each call site's target.
* <p>
* To avoid race conditions, calls to {@code setTarget} and {@code sync}
* To avoid race conditions, calls to {@code setTarget} and {@code syncAll}
* should generally be performed under some sort of mutual exclusion.
* Note that reader threads may observe an updated target as early
* as the {@code setTarget} call that install the value
* (and before the {@code sync} that confirms the value).
* (and before the {@code syncAll} that confirms the value).
* On the other hand, reader threads may observe previous versions of
* the target until the {@code sync} call returns
* the target until the {@code syncAll} call returns
* (and after the {@code setTarget} that attempts to convey the updated version).
* <p>
* This operation is likely to be expensive and should be used sparingly.
* If possible, it should be buffered for batch processing on sets of call sites.
* <p>
* If {@code sites} contains a null element,
* a {@code NullPointerException} will be raised.
* In this case, some non-null elements in the array may be
* processed before the method returns abnormally.
* Which elements these are (if any) is implementation-dependent.
*
* <h3>Java Memory Model details</h3>
* In terms of the Java Memory Model, this operation performs a synchronization
* action which is comparable in effect to the writing of a volatile variable
* by the current thread, and an eventual volatile read by every other thread
......@@ -171,18 +238,17 @@ public class MutableCallSite extends CallSite {
* thereby ensuring communication of the new target value.
* <p>
* As long as the constraints of the Java Memory Model are obeyed,
* implementations may delay the completion of a {@code sync}
* implementations may delay the completion of a {@code syncAll}
* operation while other threads ({@code T} above) continue to
* use previous values of {@code S}'s target.
* However, implementations are (as always) encouraged to avoid
* livelock, and to eventually require all threads to take account
* of the updated target.
* <p>
* This operation is likely to be expensive and should be used sparingly.
* If possible, it should be buffered for batch processing on sets of call sites.
*
* <p style="font-size:smaller;">
* (This is a static method on a set of call sites, not a
* virtual method on a single call site, for performance reasons.
* <em>Discussion:</em>
* For performance reasons, {@code syncAll} is not a virtual method
* on a single call site, but rather applies to a set of call sites.
* Some implementations may incur a large fixed overhead cost
* for processing one or more synchronization operations,
* but a small incremental cost for each additional call site.
......@@ -191,15 +257,25 @@ public class MutableCallSite extends CallSite {
* in order to make them notice the updated target value.
* However, it may be observed that a single call to synchronize
* several sites has the same formal effect as many calls,
* each on just one of the sites.)
* <p>
* each on just one of the sites.
*
* <p style="font-size:smaller;">
* <em>Implementation Note:</em>
* Simple implementations of {@code MutableCallSite} may use
* a volatile variable for the target of a mutable call site.
* In such an implementation, the {@code sync} method can be a no-op,
* In such an implementation, the {@code syncAll} method can be a no-op,
* and yet it will conform to the JMM behavior documented above.
*
* @param sites an array of call sites to be synchronized
* @throws NullPointerException if the {@code sites} array reference is null
* or the array contains a null
*/
public static void sync(MutableCallSite[] sites) {
public static void syncAll(MutableCallSite[] sites) {
if (sites.length == 0) return;
STORE_BARRIER.lazySet(0);
for (int i = 0; i < sites.length; i++) {
sites[i].getClass(); // trigger NPE on first null
}
// FIXME: NYI
}
private static final AtomicInteger STORE_BARRIER = new AtomicInteger();
......
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -27,68 +27,84 @@ package java.dyn;
/**
* <p>
* A {@code Switcher} is an object which can publish state transitions to other threads.
* A switcher is initially in the <em>valid</em> state, but may at any time be
* A {@code SwitchPoint} is an object which can publish state transitions to other threads.
* A switch point is initially in the <em>valid</em> state, but may at any time be
* changed to the <em>invalid</em> state. Invalidation cannot be reversed.
* A switch point can combine a <em>guarded pair</em> of method handles into a
* <em>guarded delegator</em>.
* The guarded delegator is a method handle which delegates to one of the old method handles.
* The state of the switch point determines which of the two gets the delegation.
* <p>
* A single switcher may be used to create any number of guarded method handle pairs.
* Each guarded pair is wrapped in a new method handle {@code M},
* which is permanently associated with the switcher that created it.
* A single switch point may be used to control any number of method handles.
* (Indirectly, therefore, it can control any number of call sites.)
* This is done by using the single switch point as a factory for combining
* any number of guarded method handle pairs into guarded delegators.
* <p>
* When a guarded delegator is created from a guarded pair, the pair
* is wrapped in a new method handle {@code M},
* which is permanently associated with the switch point that created it.
* Each pair consists of a target {@code T} and a fallback {@code F}.
* While the switcher is valid, invocations to {@code M} are delegated to {@code T}.
* While the switch point is valid, invocations to {@code M} are delegated to {@code T}.
* After it is invalidated, invocations are delegated to {@code F}.
* <p>
* Invalidation is global and immediate, as if the switcher contained a
* Invalidation is global and immediate, as if the switch point contained a
* volatile boolean variable consulted on every call to {@code M}.
* The invalidation is also permanent, which means the switcher
* The invalidation is also permanent, which means the switch point
* can change state only once.
* The switch point will always delegate to {@code F} after being invalidated.
* At that point {@code guardWithTest} may ignore {@code T} and return {@code F}.
* <p>
* Here is an example of a switcher in action:
* Here is an example of a switch point in action:
* <blockquote><pre>
MethodType MT_str2 = MethodType.methodType(String.class, String.class);
MethodHandle MH_strcat = MethodHandles.lookup()
.findVirtual(String.class, "concat", MT_str2);
Switcher switcher = new Switcher();
// the following steps may be repeated to re-use the same switcher:
SwitchPoint spt = new SwitchPoint();
// the following steps may be repeated to re-use the same switch point:
MethodHandle worker1 = strcat;
MethodHandle worker2 = MethodHandles.permuteArguments(strcat, MT_str2, 1, 0);
MethodHandle worker = switcher.guardWithTest(worker1, worker2);
MethodHandle worker = spt.guardWithTest(worker1, worker2);
assertEquals("method", (String) worker.invokeExact("met", "hod"));
switcher.invalidate();
SwitchPoint.invalidateAll(new SwitchPoint[]{ spt });
assertEquals("hodmet", (String) worker.invokeExact("met", "hod"));
* </pre></blockquote>
* <p>
* <p style="font-size:smaller;">
* <em>Discussion:</em>
* Switch points are useful without subclassing. They may also be subclassed.
* This may be useful in order to associate application-specific invalidation logic
* with the switch point.
* <p style="font-size:smaller;">
* <em>Implementation Note:</em>
* A switcher behaves as if implemented on top of {@link MutableCallSite},
* A switch point behaves as if implemented on top of {@link MutableCallSite},
* approximately as follows:
* <blockquote><pre>
public class Switcher {
public class SwitchPoint {
private static final MethodHandle
K_true = MethodHandles.constant(boolean.class, true),
K_false = MethodHandles.constant(boolean.class, false);
private final MutableCallSite mcs;
private final MethodHandle mcsInvoker;
public Switcher() {
public SwitchPoint() {
this.mcs = new MutableCallSite(K_true);
this.mcsInvoker = mcs.dynamicInvoker();
}
public MethodHandle guardWithTest(
MethodHandle target, MethodHandle fallback) {
// Note: mcsInvoker is of type boolean().
// Note: mcsInvoker is of type ()boolean.
// Target and fallback may take any arguments, but must have the same type.
return MethodHandles.guardWithTest(this.mcsInvoker, target, fallback);
}
public static void invalidateAll(Switcher[] switchers) {
List<MutableCallSite> mcss = new ArrayList<>();
for (Switcher s : switchers) mcss.add(s.mcs);
public static void invalidateAll(SwitchPoint[] spts) {
List&lt;MutableCallSite&gt; mcss = new ArrayList&lt;&gt;();
for (SwitchPoint spt : spts) mcss.add(spt.mcs);
for (MutableCallSite mcs : mcss) mcs.setTarget(K_false);
MutableCallSite.sync(mcss.toArray(new MutableCallSite[0]));
MutableCallSite.syncAll(mcss.toArray(new MutableCallSite[0]));
}
}
* </pre></blockquote>
* @author Remi Forax, JSR 292 EG
*/
public class Switcher {
public class SwitchPoint {
private static final MethodHandle
K_true = MethodHandles.constant(boolean.class, true),
K_false = MethodHandles.constant(boolean.class, false);
......@@ -96,19 +112,26 @@ public class Switcher {
private final MutableCallSite mcs;
private final MethodHandle mcsInvoker;
/** Create a switcher. */
public Switcher() {
/**
* Creates a new switch point.
*/
public SwitchPoint() {
this.mcs = new MutableCallSite(K_true);
this.mcsInvoker = mcs.dynamicInvoker();
}
/**
* Return a method handle which always delegates either to the target or the fallback.
* The method handle will delegate to the target exactly as long as the switcher is valid.
* Returns a method handle which always delegates either to the target or the fallback.
* The method handle will delegate to the target exactly as long as the switch point is valid.
* After that, it will permanently delegate to the fallback.
* <p>
* The target and fallback must be of exactly the same method type,
* and the resulting combined method handle will also be of this type.
*
* @param target the method handle selected by the switch point as long as it is valid
* @param fallback the method handle selected by the switch point after it is invalidated
* @return a combined method handle which always calls either the target or fallback
* @throws NullPointerException if either argument is null
* @see MethodHandles#guardWithTest
*/
public MethodHandle guardWithTest(MethodHandle target, MethodHandle fallback) {
......@@ -117,14 +140,56 @@ public class Switcher {
return MethodHandles.guardWithTest(mcsInvoker, target, fallback);
}
/** Set all of the given switchers into the invalid state. */
public static void invalidateAll(Switcher[] switchers) {
MutableCallSite[] sites = new MutableCallSite[switchers.length];
int fillp = 0;
for (Switcher switcher : switchers) {
sites[fillp++] = switcher.mcs;
switcher.mcs.setTarget(K_false);
/**
* Sets all of the given switch points into the invalid state.
* After this call executes, no thread will observe any of the
* switch points to be in a valid state.
* <p>
* This operation is likely to be expensive and should be used sparingly.
* If possible, it should be buffered for batch processing on sets of switch points.
* <p>
* If {@code switchPoints} contains a null element,
* a {@code NullPointerException} will be raised.
* In this case, some non-null elements in the array may be
* processed before the method returns abnormally.
* Which elements these are (if any) is implementation-dependent.
*
* <p style="font-size:smaller;">
* <em>Discussion:</em>
* For performance reasons, {@code invalidateAll} is not a virtual method
* on a single switch point, but rather applies to a set of switch points.
* Some implementations may incur a large fixed overhead cost
* for processing one or more invalidation operations,
* but a small incremental cost for each additional invalidation.
* In any case, this operation is likely to be costly, since
* other threads may have to be somehow interrupted
* in order to make them notice the updated switch point state.
* However, it may be observed that a single call to invalidate
* several switch points has the same formal effect as many calls,
* each on just one of the switch points.
*
* <p style="font-size:smaller;">
* <em>Implementation Note:</em>
* Simple implementations of {@code SwitchPoint} may use
* a private {@link MutableCallSite} to publish the state of a switch point.
* In such an implementation, the {@code invalidateAll} method can
* simply change the call site's target, and issue one call to
* {@linkplain MutableCallSite#syncAll synchronize} all the
* private call sites.
*
* @param switchPoints an array of call sites to be synchronized
* @throws NullPointerException if the {@code switchPoints} array reference is null
* or the array contains a null
*/
public static void invalidateAll(SwitchPoint[] switchPoints) {
if (switchPoints.length == 0) return;
MutableCallSite[] sites = new MutableCallSite[switchPoints.length];
for (int i = 0; i < switchPoints.length; i++) {
SwitchPoint spt = switchPoints[i];
if (spt == null) break; // MSC.syncAll will trigger a NPE
sites[i] = spt.mcs;
spt.mcs.setTarget(K_false);
}
MutableCallSite.sync(sites);
MutableCallSite.syncAll(sites);
}
}
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -34,7 +34,7 @@ import java.util.List;
* There may be a performance penalty for such tight coupling between threads.
* <p>
* Unlike {@code MutableCallSite}, there is no
* {@linkplain MutableCallSite#sync sync operation} on volatile
* {@linkplain MutableCallSite#syncAll syncAll operation} on volatile
* call sites, since every write to a volatile variable is implicitly
* synchronized with reader threads.
* <p>
......@@ -44,36 +44,68 @@ import java.util.List;
* @author John Rose, JSR 292 EG
*/
public class VolatileCallSite extends CallSite {
/** Create a call site with a volatile target.
* The initial target is set to a method handle
* of the given type which will throw {@code IllegalStateException}.
/**
* Creates a call site with a volatile binding to its target.
* The initial target is set to a method handle
* of the given type which will throw an {@code IllegalStateException} if called.
* @param type the method type that this call site will have
* @throws NullPointerException if the proposed type is null
*/
public VolatileCallSite(MethodType type) {
super(type);
}
/** Create a call site with a volatile target.
* The target is set to the given value.
/**
* Creates a call site with a volatile binding to its target.
* The target is set to the given value.
* @param target the method handle that will be the initial target of the call site
* @throws NullPointerException if the proposed target is null
*/
public VolatileCallSite(MethodHandle target) {
super(target);
}
/** Internal override to nominally final getTarget. */
@Override
MethodHandle getTarget0() {
/**
* Returns the target method of the call site, which behaves
* like a {@code volatile} field of the {@code VolatileCallSite}.
* <p>
* The interactions of {@code getTarget} with memory are the same
* as of a read from a {@code volatile} field.
* <p>
* In particular, the current thread is required to issue a fresh
* read of the target from memory, and must not fail to see
* a recent update to the target by another thread.
*
* @return the linkage state of this call site, a method handle which can change over time
* @see #setTarget
*/
@Override public final MethodHandle getTarget() {
return getTargetVolatile();
}
/**
* Set the target method of this call site, as a volatile variable.
* Has the same effect as {@link CallSite#setTarget CallSite.setTarget}, with the additional
* effects associated with volatiles, in the Java Memory Model.
* Updates the target method of this call site, as a volatile variable.
* The type of the new target must agree with the type of the old target.
* <p>
* The interactions with memory are the same as of a write to a volatile field.
* In particular, any threads is guaranteed to see the updated target
* the next time it calls {@code getTarget}.
* @param newTarget the new target
* @throws NullPointerException if the proposed new target is null
* @throws WrongMethodTypeException if the proposed new target
* has a method type that differs from the previous target
* @see #getTarget
*/
@Override public void setTarget(MethodHandle newTarget) {
checkTargetChange(getTargetVolatile(), newTarget);
setTargetVolatile(newTarget);
}
/**
* {@inheritDoc}
*/
@Override
public final MethodHandle dynamicInvoker() {
return makeDynamicInvoker();
}
}
......@@ -29,7 +29,7 @@ package java.dyn;
* Thrown to indicate that code has attempted to call a method handle
* via the wrong method type. As with the bytecode representation of
* normal Java method calls, method handle calls are strongly typed
* to a specific signature associated with a call site.
* to a specific type descriptor associated with a call site.
* <p>
* This exception may also be thrown when two method handles are
* composed, and the system detects that their types cannot be
......
......@@ -24,21 +24,20 @@
*/
/**
* This package contains dynamic language support provided directly by
* The {@code java.lang.invoke} package contains dynamic language support provided directly by
* the Java core class libraries and virtual machine.
*
* <p style="font-size:smaller;">
* <em>Historic Note:</em> In some early versions of Java SE 7,
* the name of this package is {@code java.dyn}.
* <p>
* Certain types in this package have special relations to dynamic
* language support in the virtual machine:
* <ul>
* <li>In source code, a call to
* {@link java.dyn.MethodHandle#invokeExact MethodHandle.invokeExact} or
* {@link java.dyn.MethodHandle#invokeGeneric MethodHandle.invokeGeneric}
* will compile and link, regardless of the requested type signature.
* As usual, the Java compiler emits an {@code invokevirtual}
* instruction with the given signature against the named method.
* The JVM links any such call (regardless of signature) to a dynamically
* typed method handle invocation. In the case of {@code invokeGeneric},
* argument and return value conversions are applied.
* <li>The class {@link java.dyn.MethodHandle MethodHandle} contains
* <a href="MethodHandle.html#sigpoly">signature polymorphic methods</a>
* which can be linked regardless of their type descriptor.
* Normally, method linkage requires exact matching of type descriptors.
* </li>
*
* <li>The JVM bytecode format supports immediate constants of
......@@ -58,12 +57,11 @@
* The final two bytes are reserved for future use and required to be zero.
* The constant pool reference of an {@code invokedynamic} instruction is to a entry
* with tag {@code CONSTANT_InvokeDynamic} (decimal 18). See below for its format.
* (The tag value 17 is also temporarily allowed. See below.)
* The entry specifies the following information:
* <ul>
* <li>a bootstrap method (a {@link java.dyn.MethodHandle MethodHandle} constant)</li>
* <li>the dynamic invocation name (a UTF8 string)</li>
* <li>the argument and return types of the call (encoded as a signature in a UTF8 string)</li>
* <li>the argument and return types of the call (encoded as a type descriptor in a UTF8 string)</li>
* <li>optionally, a sequence of additional <em>static arguments</em> to the bootstrap method ({@code ldc}-type constants)</li>
* </ul>
* <p>
......@@ -78,9 +76,9 @@
* as <a href="#bsm">described below</a>.
*
* <p style="font-size:smaller;">
* (Historic Note: Some older JVMs may allow the index of a {@code CONSTANT_NameAndType}
* <em>Historic Note:</em> Some older JVMs may allow the index of a {@code CONSTANT_NameAndType}
* instead of a {@code CONSTANT_InvokeDynamic}. In earlier, obsolete versions of this API, the
* bootstrap method was specified dynamically, in a per-class basis, during class initialization.)
* bootstrap method was specified dynamically, in a per-class basis, during class initialization.
*
* <h3><a name="indycon"></a>constant pool entries for {@code invokedynamic} instructions</h3>
* If a constant pool entry has the tag {@code CONSTANT_InvokeDynamic} (decimal 18),
......@@ -90,33 +88,21 @@
* <em>bootstrap method table</em>, which is stored in the {@code BootstrapMethods}
* attribute as <a href="#bsmattr">described below</a>.
* The second pair of bytes must be an index to a {@code CONSTANT_NameAndType}.
* This table is not part of the constant pool. Instead, it is stored
* in a class attribute named {@code BootstrapMethods}, described below.
* <p>
* The first index specifies a bootstrap method used by the associated dynamic call sites.
* The second index specifies the method name, argument types, and return type of the dynamic call site.
* The structure of such an entry is therefore analogous to a {@code CONSTANT_Methodref},
* except that the bootstrap method specifier reference replaces
* the {@code CONSTANT_Class} reference of a {@code CONSTANT_Methodref} entry.
* <p>
* Some older JVMs may allow an older constant pool entry tag of decimal 17.
* The format and behavior of a constant pool entry with this tag is identical to
* an entry with a tag of decimal 18, except that the first index refers directly
* to a {@code CONSTANT_MethodHandle} to use as the bootstrap method.
* This format does not require the bootstrap method table.
*
* <p style="font-size:smaller;">
* <em>(Note: The Proposed Final Draft of this specification is likely to support
* only the tag 18, not the tag 17.)</em>
*
* <h3><a name="mtcon"></a>constant pool entries for {@linkplain java.dyn.MethodType method types}</h3>
* If a constant pool entry has the tag {@code CONSTANT_MethodType} (decimal 16),
* it must contain exactly two more bytes, which must be an index to a {@code CONSTANT_Utf8}
* entry which represents a method type signature.
* entry which represents a method type descriptor.
* <p>
* The JVM will ensure that on first
* execution of an {@code ldc} instruction for this entry, a {@link java.dyn.MethodType MethodType}
* will be created which represents the signature.
* will be created which represents the type descriptor.
* Any classes mentioned in the {@code MethodType} will be loaded if necessary,
* but not initialized.
* Access checking and error reporting is performed exactly as it is for
......@@ -144,24 +130,58 @@
* The method handle itself will have a type and behavior determined by the subtag as follows:
* <code>
* <table border=1 cellpadding=5 summary="CONSTANT_MethodHandle subtypes">
* <tr><th>N</th><th>subtag name</th><th>member</th><th>MH type</th><th>MH behavior</th></tr>
* <tr><td>1</td><td>REF_getField</td><td>C.f:T</td><td>(C)T</td><td>getfield C.f:T</td></tr>
* <tr><td>2</td><td>REF_getStatic</td><td>C.f:T</td><td>(&nbsp;)T</td><td>getstatic C.f:T</td></tr>
* <tr><td>3</td><td>REF_putField</td><td>C.f:T</td><td>(C,T)void</td><td>putfield C.f:T</td></tr>
* <tr><td>4</td><td>REF_putStatic</td><td>C.f:T</td><td>(T)void</td><td>putstatic C.f:T</td></tr>
* <tr><td>5</td><td>REF_invokeVirtual</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokevirtual C.m(A*)T</td></tr>
* <tr><td>6</td><td>REF_invokeStatic</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokestatic C.m(A*)T</td></tr>
* <tr><td>7</td><td>REF_invokeSpecial</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokespecial C.m(A*)T</td></tr>
* <tr><td>8</td><td>REF_newInvokeSpecial</td><td>C.&lt;init&gt;(A*)void</td><td>(A*)C</td><td>new C; dup; invokespecial C.&lt;init&gt;(A*)void</td></tr>
* <tr><td>9</td><td>REF_invokeInterface</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokeinterface C.m(A*)T</td></tr>
* <tr><th>N</th><th>subtag name</th><th>member</th><th>MH type</th><th>bytecode behavior</th><th>lookup expression</th></tr>
* <tr><td>1</td><td>REF_getField</td><td>C.f:T</td><td>(C)T</td><td>getfield C.f:T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findGetter findGetter(C.class,"f",T.class)}</td></tr>
* <tr><td>2</td><td>REF_getStatic</td><td>C.f:T</td><td>(&nbsp;)T</td><td>getstatic C.f:T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findStaticGetter findStaticGetter(C.class,"f",T.class)}</td></tr>
* <tr><td>3</td><td>REF_putField</td><td>C.f:T</td><td>(C,T)void</td><td>putfield C.f:T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findSetter findSetter(C.class,"f",T.class)}</td></tr>
* <tr><td>4</td><td>REF_putStatic</td><td>C.f:T</td><td>(T)void</td><td>putstatic C.f:T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findStaticSetter findStaticSetter(C.class,"f",T.class)}</td></tr>
* <tr><td>5</td><td>REF_invokeVirtual</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokevirtual C.m(A*)T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findVirtual findVirtual(C.class,"m",MT)}</td></tr>
* <tr><td>6</td><td>REF_invokeStatic</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokestatic C.m(A*)T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findStatic findStatic(C.class,"m",MT)}</td></tr>
* <tr><td>7</td><td>REF_invokeSpecial</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokespecial C.m(A*)T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findSpecial findSpecial(C.class,"m",MT,this.class)}</td></tr>
* <tr><td>8</td><td>REF_newInvokeSpecial</td><td>C.&lt;init&gt;(A*)void</td><td>(A*)C</td><td>new C; dup; invokespecial C.&lt;init&gt;(A*)void</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findConstructor findConstructor(C.class,MT)}</td></tr>
* <tr><td>9</td><td>REF_invokeInterface</td><td>C.m(A*)T</td><td>(C,A*)T</td><td>invokeinterface C.m(A*)T</td>
* <td>{@linkplain java.dyn.MethodHandles.Lookup#findVirtual findVirtual(C.class,"m",MT)}</td></tr>
* </table>
* </code>
* Here, the type {@code C} is taken from the {@code CONSTANT_Class} reference associated
* with the {@code CONSTANT_NameAndType} descriptor.
* The field name {@code f} or method name {@code m} is taken from the {@code CONSTANT_NameAndType}
* as is the result type {@code T} and (in the case of a method or constructor) the argument type sequence
* {@code A*}.
* <p>
* Each method handle constant has an equivalent instruction sequence called its <em>bytecode behavior</em>.
* In general, creating a method handle constant can be done in exactly the same circumstances that
* the JVM would successfully resolve the symbolic references in the bytecode behavior.
* Also, the type of a method handle constant is such that a valid {@code invokeExact} call
* on the method handle has exactly the same JVM stack effects as the <em>bytecode behavior</em>.
* Finally, calling a method handle constant on a valid set of arguments has exactly the same effect
* and returns the same result (if any) as the corresponding <em>bytecode behavior</em>.
* <p>
* Each method handle constant also has an equivalent reflective <em>lookup expression</em>,
* which is a query to a method in {@link java.dyn.MethodHandles.Lookup}.
* In the example lookup method expression given in the table above, the name {@code MT}
* stands for a {@code MethodType} built from {@code T} and the sequence of argument types {@code A*}.
* (Note that the type {@code C} is not prepended to the query type {@code MT} even if the member is non-static.)
* In the case of {@code findSpecial}, the name {@code this.class} refers to the class containing
* the bytecodes.
* <p>
* The special name {@code <clinit>} is not allowed.
* The special name {@code <init>} is not allowed except for subtag 8 as shown.
* <p>
* The JVM verifier and linker apply the same access checks and restrictions for these references as for the hypothetical
* bytecode instructions specified in the last column of the table. In particular, method handles to
* bytecode instructions specified in the last column of the table.
* A method handle constant will successfully resolve to a method handle if the symbolic references
* of the corresponding bytecode instruction(s) would also resolve successfully.
* Otherwise, an attempt to resolve the constant will throw equivalent linkage errors.
* In particular, method handles to
* private and protected members can be created in exactly those classes for which the corresponding
* normal accesses are legal.
* <p>
......@@ -186,14 +206,14 @@
* by the execution of {@code invokedynamic} and {@code ldc} instructions.
* (Roughly speaking, this means that every use of a constant pool entry
* must lead to the same outcome.
* If the resoultion succeeds, the same object reference is produced
* If the resolution succeeds, the same object reference is produced
* by every subsequent execution of the same instruction.
* If the resolution of the constant causes an error to occur,
* the same error will be re-thrown on every subsequent attempt
* to use this particular constant.)
* <p>
* Constants created by the resolution of these constant pool types are not necessarily
* interned. Except for {@link CONSTANT_Class} and {@link CONSTANT_String} entries,
* interned. Except for {@code CONSTANT_Class} and {@code CONSTANT_String} entries,
* two distinct constant pool entries might not resolve to the same reference
* even if they contain the same symbolic reference.
*
......@@ -207,31 +227,31 @@
* <p>
* Each {@code invokedynamic} instruction statically specifies its own
* bootstrap method as a constant pool reference.
* The constant pool reference also specifies the call site's name and type signature,
* The constant pool reference also specifies the call site's name and type descriptor,
* just like {@code invokevirtual} and the other invoke instructions.
* <p>
* Linking starts with resolving the constant pool entry for the
* bootstrap method, and resolving a {@link java.dyn.MethodType MethodType} object for
* the type signature of the dynamic call site.
* the type descriptor of the dynamic call site.
* This resolution process may trigger class loading.
* It may therefore throw an error if a class fails to load.
* This error becomes the abnormal termination of the dynamic
* call site execution.
* Linkage does not trigger class initialization.
* <p>
* Next, the bootstrap method call is started, with four or five values being stacked:
* Next, the bootstrap method call is started, with at least four values being stacked:
* <ul>
* <li>a {@code MethodHandle}, the resolved bootstrap method itself </li>
* <li>a {@code MethodHandles.Lookup}, a lookup object on the <em>caller class</em> in which dynamic call site occurs </li>
* <li>a {@code String}, the method name mentioned in the call site </li>
* <li>a {@code MethodType}, the resolved type signature of the call </li>
* <li>optionally, a single object representing one or more <a href="#args">additional static arguments</a> </li>
* <li>a {@code MethodType}, the resolved type descriptor of the call </li>
* <li>optionally, one or more <a href="#args">additional static arguments</a> </li>
* </ul>
* The method handle is then applied to the other values as if by
* {@link java.dyn.MethodHandle#invokeGeneric invokeGeneric}.
* The returned result must be a {@link java.dyn.CallSite CallSite} (or a subclass).
* The type of the call site's target must be exactly equal to the type
* derived from the dynamic call site signature and passed to
* derived from the dynamic call site's type descriptor and passed to
* the bootstrap method.
* The call site then becomes permanently linked to the dynamic call site.
* <p>
......@@ -299,11 +319,11 @@
* chosen target object.
*
* <p style="font-size:smaller;">
* (Historic Note: Unlike some previous versions of this specification,
* <em>Historic Note:</em> Unlike some previous versions of this specification,
* these rules do not enable the JVM to duplicate dynamic call sites,
* or to issue &ldquo;causeless&rdquo; bootstrap method calls.
* Every dynamic call site transitions at most once from unlinked to linked,
* just before its first invocation.)
* just before its first invocation.
*
* <h3><a name="bsmattr">the {@code BootstrapMethods} attribute </h3>
* Each {@code CONSTANT_InvokeDynamic} entry contains an index which references
......@@ -349,7 +369,6 @@
* Static arguments are specified constant pool indexes stored in the {@code BootstrapMethods} attribute.
* Before the bootstrap method is invoked, each index is used to compute an {@code Object}
* reference to the indexed value in the constant pool.
* If the value is a primitive type, it is converted to a reference by boxing conversion.
* The valid constant pool entries are listed in this table:
* <code>
* <table border=1 cellpadding=5 summary="Static argument types">
......@@ -374,6 +393,9 @@
* at most 252 extra arguments can be supplied.)
* The bootstrap method will be invoked as if by either {@code invokeGeneric}
* or {@code invokeWithArguments}. (There is no way to tell the difference.)
* <p>
* The normal argument conversion rules for {@code invokeGeneric} apply to all stacked arguments.
* For example, if a pushed value is a primitive type, it may be converted to a reference by boxing conversion.
* If the bootstrap method is a variable arity method (its modifier bit {@code 0x0080} is set),
* then some or all of the arguments specified here may be collected into a trailing array parameter.
* (This is not a special rule, but rather a useful consequence of the interaction
......@@ -430,11 +452,6 @@ struct CONSTANT_MethodType_info {
u1 tag = 16;
u2 descriptor_index; // index to CONSTANT_Utf8, as in NameAndType
}
struct CONSTANT_InvokeDynamic_17_info {
u1 tag = 17;
u2 bootstrap_method_index; // index to CONSTANT_MethodHandle
u2 name_and_type_index; // same as for CONSTANT_Methodref, etc.
}
struct CONSTANT_InvokeDynamic_info {
u1 tag = 18;
u2 bootstrap_method_attr_index; // index into BootstrapMethods_attr
......@@ -451,9 +468,6 @@ struct BootstrapMethods_attr {
} bootstrap_methods[bootstrap_method_count];
}
* </pre></blockquote>
* <p>
* <em>Note: The Proposed Final Draft of JSR 292 may remove the constant tag 17,
* for the sake of simplicity.</em>
*
* @author John Rose, JSR 292 EG
*/
......
......@@ -962,7 +962,7 @@ public class AdapterMethodHandle extends BoundMethodHandle {
@Override
public String toString() {
return nonAdapter((MethodHandle)vmtarget).toString();
return MethodHandleImpl.getNameString(IMPL_TOKEN, nonAdapter((MethodHandle)vmtarget), this);
}
private static MethodHandle nonAdapter(MethodHandle mh) {
......
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -28,6 +28,7 @@ package sun.dyn;
import java.dyn.*;
import java.lang.reflect.*;
import sun.dyn.util.*;
import static sun.dyn.MethodTypeImpl.invokers;
/**
* Adapters which mediate between incoming calls which are generic
......@@ -128,7 +129,7 @@ class FromGeneric {
MethodType targetType, MethodType internalType) {
// All the adapters we have here have reference-untyped internal calls.
assert(internalType == internalType.erase());
MethodHandle invoker = MethodHandles.exactInvoker(targetType);
MethodHandle invoker = invokers(targetType).exactInvoker();
// cast all narrow reference types, unbox all primitive arguments:
MethodType fixArgsType = internalType.changeReturnType(targetType.returnType());
MethodHandle fixArgs = AdapterMethodHandle.convertArguments(Access.TOKEN,
......
......@@ -28,6 +28,7 @@ package sun.dyn;
import java.dyn.*;
import java.lang.reflect.*;
import sun.dyn.util.*;
import static sun.dyn.MethodTypeImpl.invokers;
/**
* Adapters which manage MethodHanndle.invokeGeneric calls.
......@@ -87,7 +88,7 @@ class InvokeGeneric {
private MethodHandle makePostDispatchInvoker() {
// Take (MH'; MT, MH; A...) and run MH'(MT, MH; A...).
MethodType invokerType = erasedCallerType.insertParameterTypes(0, EXTRA_ARGS);
return MethodHandles.exactInvoker(invokerType);
return invokers(invokerType).exactInvoker();
}
private MethodHandle dropDispatchArguments(MethodHandle targetInvoker) {
assert(targetInvoker.type().parameterType(0) == MethodHandle.class);
......
......@@ -104,8 +104,7 @@ public class Invokers {
MethodHandle vaInvoker = spreadInvokers[objectArgCount];
if (vaInvoker != null) return vaInvoker;
MethodHandle gInvoker = genericInvoker();
MethodType vaType = MethodType.genericMethodType(objectArgCount, true);
vaInvoker = MethodHandles.spreadArguments(gInvoker, invokerType(vaType));
vaInvoker = gInvoker.asSpreader(Object[].class, targetType.parameterCount() - objectArgCount);
spreadInvokers[objectArgCount] = vaInvoker;
return vaInvoker;
}
......
......@@ -136,6 +136,8 @@ public abstract class MethodHandleImpl {
}
static {
if (!MethodHandleNatives.JVM_SUPPORT) // force init of native API
throw new InternalError("No JVM support for JSR 292");
// Force initialization of Lookup, so it calls us back as initLookup:
MethodHandles.publicLookup();
if (IMPL_LOOKUP_INIT == null)
......@@ -1216,14 +1218,24 @@ public abstract class MethodHandleImpl {
}
static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
public static String getNameString(Access token, MethodHandle target) {
public static String getNameString(Access token, MethodHandle target, Object type) {
Access.check(token);
if (!(type instanceof MethodType)) {
if (type == null)
type = target.type();
else if (type instanceof MethodHandle)
type = ((MethodHandle)type).type();
}
MemberName name = null;
if (target != null)
name = MethodHandleNatives.getMethodName(target);
if (name == null)
return "invoke" + target.type();
return name.getName() + target.type();
return "invoke" + type;
return name.getName() + type;
}
public static String getNameString(Access token, MethodHandle target) {
return getNameString(token, target, null);
}
static String addTypeString(Object obj, MethodHandle target) {
......
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -31,6 +31,7 @@ import java.lang.reflect.InvocationTargetException;
import sun.dyn.util.ValueConversions;
import sun.dyn.util.Wrapper;
import static sun.dyn.MemberName.newIllegalArgumentException;
import static sun.dyn.MethodTypeImpl.invokers;
/**
* Adapters which mediate between incoming calls which are not generic
......@@ -72,7 +73,7 @@ class ToGeneric {
assert(entryType.erase() == entryType); // for now
// incoming call will first "forget" all reference types except Object
this.entryType = entryType;
MethodHandle invoker0 = MethodHandles.exactInvoker(entryType.generic());
MethodHandle invoker0 = invokers(entryType.generic()).exactInvoker();
MethodType rawEntryTypeInit;
Adapter ad = findAdapter(rawEntryTypeInit = entryType);
if (ad != null) {
......
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.dyn;
import java.dyn.MethodHandle;
/**
* Private API used inside of java.dyn.MethodHandles.
* Interface implemented by every object which is produced by
* {@link java.dyn.MethodHandles#asInstance MethodHandles.asInstance}.
* The methods of this interface allow a caller to recover the parameters
* to {@code asInstance}.
* This allows applications to repeatedly convert between method handles
* and SAM objects, without the risk of creating unbounded delegation chains.
*/
public interface WrapperInstance {
/** Produce or recover a target method handle which is behaviorally
* equivalent to the SAM method of this object.
*/
public MethodHandle getWrapperInstanceTarget();
/** Recover the SAM type for which this object was created.
*/
public Class<?> getWrapperInstanceType();
}
......@@ -320,7 +320,7 @@ public class InvokeGenericTest {
MethodHandle callable(List<Class<?>> params) {
MethodHandle mh = CALLABLES.get(params);
if (mh == null) {
mh = collectArguments(collector_MH, methodType(Object.class, params));
mh = collector_MH.asType(methodType(Object.class, params));
CALLABLES.put(params, mh);
}
return mh;
......
......@@ -151,8 +151,8 @@ MethodHandles.Lookup lookup = MethodHandles.lookup();
// mt is (char,char)String
mt = MethodType.methodType(String.class, char.class, char.class);
mh = lookup.findVirtual(String.class, "replace", mt);
// (Ljava/lang/String;CC)Ljava/lang/String;
s = (String) mh.invokeExact("daddy",'d','n');
// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
assert(s.equals("nanny"));
// weakly typed invocation (using MHs.invoke)
s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
......@@ -162,23 +162,24 @@ mt = MethodType.methodType(java.util.List.class, Object[].class);
mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
assert(mh.isVarargsCollector());
x = mh.invokeGeneric("one", "two");
// invokeGeneric(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
assert(x.equals(java.util.Arrays.asList("one","two")));
// mt is (Object,Object,Object)Object
mt = MethodType.genericMethodType(3);
mh = MethodHandles.collectArguments(mh, mt);
// mt is (Object,Object,Object)Object
// (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
mh = mh.asType(mt);
x = mh.invokeExact((Object)1, (Object)2, (Object)3);
// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
assert(x.equals(java.util.Arrays.asList(1,2,3)));
// mt is { =&gt; int}
mt = MethodType.methodType(int.class);
mh = lookup.findVirtual(java.util.List.class, "size", mt);
// (Ljava/util/List;)I
i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
// invokeExact(Ljava/util/List;)I
assert(i == 3);
mt = MethodType.methodType(void.class, String.class);
mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
mh.invokeExact(System.out, "Hello, world.");
// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
{}
}}
}
......@@ -206,9 +207,7 @@ assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
MethodHandle vamh = publicLookup()
.findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
.asVarargsCollector(Object[].class);
MethodHandle invokeExact = publicLookup()
.findVirtual(MethodHandle.class, "invokeExact", vamh.type());
MethodHandle mh = invokeExact.bindTo(vamh);
MethodHandle mh = MethodHandles.exactInvoker(vamh.type()).bindTo(vamh);
assert(vamh.type().equals(mh.type()));
assertEquals("[1, 2, 3]", vamh.invokeGeneric(1,2,3).toString());
boolean failed = false;
......
......@@ -323,6 +323,44 @@ public class MethodHandlesTest {
return x.getClass().getSimpleName();
}
/** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
static MethodHandle varargsList(int arity) {
return ValueConversions.varargsList(arity);
}
/** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
static MethodHandle varargsArray(int arity) {
return ValueConversions.varargsArray(arity);
}
/** Variation of varargsList, but with the given rtype. */
static MethodHandle varargsList(int arity, Class<?> rtype) {
MethodHandle list = varargsList(arity);
MethodType listType = list.type().changeReturnType(rtype);
if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
// OK
} else if (rtype.isAssignableFrom(String.class)) {
if (LIST_TO_STRING == null)
try {
LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
MethodType.methodType(String.class, List.class));
} catch (Exception ex) { throw new RuntimeException(ex); }
list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
} else if (rtype.isPrimitive()) {
if (LIST_TO_INT == null)
try {
LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
MethodType.methodType(int.class, List.class));
} catch (Exception ex) { throw new RuntimeException(ex); }
list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
list = MethodHandles.explicitCastArguments(list, listType);
} else {
throw new RuntimeException("varargsList: "+rtype);
}
return list.asType(listType);
}
private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
private static String listToString(List x) { return x.toString(); }
private static int listToInt(List x) { return x.toString().hashCode(); }
static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
return changeArgTypes(target, 0, 999, argType);
}
......@@ -1302,7 +1340,7 @@ public class MethodHandlesTest {
}
MethodType inType = MethodType.methodType(Object.class, types);
MethodType outType = MethodType.methodType(Object.class, permTypes);
MethodHandle target = MethodHandles.convertArguments(ValueConversions.varargsList(outargs), outType);
MethodHandle target = MethodHandles.convertArguments(varargsList(outargs), outType);
MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
Object result = newTarget.invokeWithArguments(args);
Object expected = Arrays.asList(permArgs);
......@@ -1329,7 +1367,7 @@ public class MethodHandlesTest {
}
public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
countTest();
MethodHandle target = ValueConversions.varargsArray(nargs);
MethodHandle target = varargsArray(nargs);
MethodHandle target2 = changeArgTypes(target, argType);
if (verbosity >= 3)
System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
......@@ -1359,7 +1397,7 @@ public class MethodHandlesTest {
spreadParams.clear(); spreadParams.add(Object[].class);
}
MethodType newType = MethodType.methodType(Object.class, newParams);
MethodHandle result = MethodHandles.spreadArguments(target2, newType);
MethodHandle result = target2.asSpreader(Object[].class, nargs-pos).asType(newType);
Object[] returnValue;
if (pos == 0) {
// In the following line, the first cast implies
......@@ -1393,7 +1431,7 @@ public class MethodHandlesTest {
public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
countTest();
// fake up a MH with the same type as the desired adapter:
MethodHandle fake = ValueConversions.varargsArray(nargs);
MethodHandle fake = varargsArray(nargs);
fake = changeArgTypes(fake, argType);
MethodType newType = fake.type();
Object[] args = randomArgs(newType.parameterArray());
......@@ -1401,12 +1439,12 @@ public class MethodHandlesTest {
Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
// here is the MH which will witness the collected argument tail:
MethodHandle target = ValueConversions.varargsArray(pos+1);
MethodHandle target = varargsArray(pos+1);
target = changeArgTypes(target, 0, pos, argType);
target = changeArgTypes(target, pos, pos+1, Object[].class);
if (verbosity >= 3)
System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
MethodHandle result = MethodHandles.collectArguments(target, newType);
MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
Object[] returnValue = (Object[]) result.invokeWithArguments(args);
// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
......@@ -1430,7 +1468,7 @@ public class MethodHandlesTest {
void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
countTest();
MethodHandle target = ValueConversions.varargsArray(nargs + ins);
MethodHandle target = varargsArray(nargs + ins);
Object[] args = randomArgs(target.type().parameterArray());
List<Object> resList = Arrays.asList(args);
List<Object> argsToPass = new ArrayList<Object>(resList);
......@@ -1449,6 +1487,55 @@ public class MethodHandlesTest {
assertEquals(resList, res2List);
}
@Test
public void testFilterReturnValue() throws Throwable {
if (CAN_SKIP_WORKING) return;
startTest("filterReturnValue");
Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
assertTrue(List.class.isAssignableFrom(classOfVCList));
for (int nargs = 0; nargs <= 3; nargs++) {
for (Class<?> rtype : new Class[] { Object.class,
List.class,
int.class,
//byte.class, //FIXME: add this
//long.class, //FIXME: add this
CharSequence.class,
String.class }) {
testFilterReturnValue(nargs, rtype);
}
}
}
void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
countTest();
MethodHandle target = varargsList(nargs, rtype);
MethodHandle filter;
if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
filter = varargsList(1); // add another layer of list-ness
else
filter = MethodHandles.identity(rtype);
filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
Object[] argsToPass = randomArgs(nargs, Object.class);
if (verbosity >= 3)
System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
if (verbosity >= 4)
System.out.println("filtered target: "+target2);
// Simulate expected effect of filter on return value:
Object unfiltered = target.invokeWithArguments(argsToPass);
Object expected = filter.invokeWithArguments(unfiltered);
if (verbosity >= 4)
System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
if (verbosity >= 4)
System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
Object result = target2.invokeWithArguments(argsToPass);
if (verbosity >= 3)
System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
if (!expected.equals(result))
System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
assertEquals(expected, result);
}
@Test
public void testFilterArguments() throws Throwable {
if (CAN_SKIP_WORKING) return;
......@@ -1462,8 +1549,8 @@ public class MethodHandlesTest {
void testFilterArguments(int nargs, int pos) throws Throwable {
countTest();
MethodHandle target = ValueConversions.varargsList(nargs);
MethodHandle filter = ValueConversions.varargsList(1);
MethodHandle target = varargsList(nargs);
MethodHandle filter = varargsList(1);
filter = MethodHandles.convertArguments(filter, filter.type().generic());
Object[] argsToPass = randomArgs(nargs, Object.class);
if (verbosity >= 3)
......@@ -1477,7 +1564,7 @@ public class MethodHandlesTest {
if (verbosity >= 3)
System.out.println("result: "+result);
if (!expected.equals(result))
System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+argsToPass+" => "+result);
System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
assertEquals(expected, result);
}
......@@ -1497,8 +1584,8 @@ public class MethodHandlesTest {
void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
if (pos != 0) return; // can fold only at pos=0 for now
countTest();
MethodHandle target = ValueConversions.varargsList(1 + nargs);
MethodHandle combine = ValueConversions.varargsList(fold).asType(MethodType.genericMethodType(fold));
MethodHandle target = varargsList(1 + nargs);
MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
if (verbosity >= 3)
System.out.println("fold "+target+" with "+combine);
......@@ -1514,7 +1601,7 @@ public class MethodHandlesTest {
if (verbosity >= 3)
System.out.println("result: "+result);
if (!expected.equals(result))
System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result);
System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
assertEquals(expected, result);
}
......@@ -1533,7 +1620,7 @@ public class MethodHandlesTest {
void testDropArguments(int nargs, int pos, int drop) throws Throwable {
countTest();
MethodHandle target = ValueConversions.varargsArray(nargs);
MethodHandle target = varargsArray(nargs);
Object[] args = randomArgs(target.type().parameterArray());
MethodHandle target2 = MethodHandles.dropArguments(target, pos,
Collections.nCopies(drop, Object.class).toArray(new Class[0]));
......@@ -1584,7 +1671,8 @@ public class MethodHandlesTest {
boolean testRetCode = type.returnType() != void.class;
MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
MethodType.genericMethodType(0, true));
target = MethodHandles.collectArguments(target, type);
assertTrue(target.isVarargsCollector());
target = target.asType(type);
Object[] args = randomArgs(type.parameterArray());
List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
targetPlusArgs.add(0, target);
......@@ -1808,7 +1896,7 @@ public class MethodHandlesTest {
MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
while (thrower.type().parameterCount() < nargs)
thrower = MethodHandles.dropArguments(thrower, thrower.type().parameterCount(), Object.class);
MethodHandle catcher = ValueConversions.varargsList(1+nargs).asType(MethodType.genericMethodType(1+nargs));
MethodHandle catcher = varargsList(1+nargs).asType(MethodType.genericMethodType(1+nargs));
MethodHandle target = MethodHandles.catchException(thrower,
thrown.getClass(), catcher);
assertEquals(thrower.type(), target.type());
......@@ -2079,7 +2167,7 @@ public class MethodHandlesTest {
CharSequence.class,
Example.class }) {
try {
MethodHandles.asInstance(ValueConversions.varargsArray(0), nonSAM);
MethodHandles.asInstance(varargsArray(0), nonSAM);
System.out.println("Failed to throw");
assertTrue(false);
} catch (IllegalArgumentException ex) {
......@@ -2183,22 +2271,22 @@ class ValueConversions {
Object a8, Object a9)
{ return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
static MethodHandle[] makeLists() {
ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
ArrayList<MethodHandle> lists = new ArrayList<MethodHandle>();
MethodHandles.Lookup lookup = IMPL_LOOKUP;
for (;;) {
int nargs = arrays.size();
int nargs = lists.size();
MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
String name = "list";
MethodHandle array = null;
MethodHandle list = null;
try {
array = lookup.findStatic(ValueConversions.class, name, type);
list = lookup.findStatic(ValueConversions.class, name, type);
} catch (NoAccessException ex) {
}
if (array == null) break;
arrays.add(array);
if (list == null) break;
lists.add(list);
}
assert(arrays.size() == 11); // current number of methods
return arrays.toArray(new MethodHandle[0]);
assert(lists.size() == 11); // current number of methods
return lists.toArray(new MethodHandle[0]);
}
static final MethodHandle[] LISTS = makeLists();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册