The tryFinally combinator (from java.lang.invoke.MethodHandles) is competent to perform locking and unlocking of mutexes, except for the JVM's built-in synchronization mechanism. I.e., there is no way to put a monitorexit instruction in a finally block incorporated into a tryFinally method handle.
We should supply an API point for introducing a monitor enter/exit pair into a try-finally structure in a method handle. Proposal:
/** Makes a method handle that adapts a {@ code target} method handle by wrapping it in a {@ code try-finally} block, where a monitor-enter instruction precedes the execution of the target, and a monitor-exit instruction is executed on all normal and exceptional paths after the block.
The monitor enter and exit instructions are applied to an object selected by the {@ code objectSelector}, which is applied on the same arguments as target. The {@ code objectSelector} must return a reference type. Its argument list must be no longer than that of {@ code target}, and argument lists must be pairwise identical, up to the shorter of the two.
<blockquote><pre>{@code
V target(A..., B...);
R objectSelector(A...);
V adapter(A... a, B... b) {
R object = objectSelector(a...);
synchronized (object) {
return target(a..., b...);
}
}
}</pre></blockquote>
*/
public static MethodHandle monitorEnterExit(MethodHandle target, MethodHandle objectSelector) { ... }