[foreign-memaccess+abi] RFR: Improve ResourceScope javadoc
Maurizio Cimadamore
mcimadamore at openjdk.java.net
Tue Apr 20 10:49:09 UTC 2021
On Tue, 20 Apr 2021 09:44:30 GMT, Maurizio Cimadamore <mcimadamore at openjdk.org> wrote:
> > Regarding `GLOBAL_SCOPE.acquire`, it seems harmless. Writing uniform scope logic might get harder if the global scope behaves differently, but i don't have a strong sense of how libraries might operate on scope.s It might well be the case if something accepts and wraps a segment e.g. a matrix whose element buffer is allocated independently/externally and it needs to be kept alive for the life time of the matrix.
>
> Not just about GLOBAL_SCOPE - but also about newImplicitScope. Yes, there is a tension between uniform usage and how meaningful these operations are. My intuition was to exploit a trick of try with resources which is tolerant to `null`s.
>
> So, if you do
>
> ```
> try (var handle = scope.acquire()) {
> ...
> }
> ```
>
> And, sometimes, the handle is null, the TWR is still valid (javac inserts a null check in the finalizer), but at least you don't have an odd handle on your hands which doesn't really do what it says on the tin (e.g. calling `Handle::close` does nothing).
On this topic, I think an API change that I've been considering recently might help things a bit:
var handle = scope.acquire();
try {
// critical region
} finally {
scope.release(handle);
}
This is lower level, and doesn't expose try with resources. It's not a big deal, I think, as using try with resources in the way the current API suggests generates annoying warnings (as the handle is never used inside the try block). The nice thing about this approach is that we can:
* return a dummy handle (e.g. a constant, well known to the system) for all implicit scopes
* in idiomatic code, the scope is always reachable at the end of the try/finally
In other words, writing code this way will make it work, both when deterministic deallocation is used (because acquire will return a "real" handle) and when implicit deallocation is used (because the scope is still reachable, so its resources cannot be freed by the GC in the middle of the try block).
I think removing the `close` method from `Handle` mitigates a lot of the concerns I have on the current acquire API. If this looks good I can pursue in a separate patch.
For the records, if not using try-with-resources ends up being too annoying, we can always add an high-order function which does acquire/release on top. But current experiments with async IO don't seem to suggest that this is an issue.
-------------
PR: https://git.openjdk.java.net/panama-foreign/pull/510
More information about the panama-dev
mailing list