java icon indicating copy to clipboard operation
java copied to clipboard

Resource scopes draft

Open rnett opened this issue 4 years ago • 4 comments
trafficstars

This is a rough draft of resource scopes. It's not fully implemented or used anywhere, but the deallocation behavior and API are there, and that's mostly what I want comments on. Synchronization can probably be done better, too, but not to much should change (suggestions on that are welcome if you notice anything that sticks out).

There's four variants from two variables: implicit/explicit and strong/weak. Implicit/explicit controls whether the scope itself is GC'd (unlike panama, you can still manually close implicit scopes). Strong/weak controls whether the resources will be GC'd. A strong scope holds on to all of it's references and dereferences them on close, while a weak scope only holds onto them weakly, and thus only dereferences the ones that are still reachable at close. This can result in some resources being deallocated after their scope closes, which is why I provide the option for strong scopes, but it's mostly fine.

I've considered getting rid of implicit/explicit and just making all scopes be closed on GC, but I assume there's a reason panama didn't do that. I don't think we would run into the same issues since we're reference counting: even if a scope is GC'd, its resources would only be deallocated if there were no other scopes referencing them, but I'm not sure enough to remove it.

I also have addDependency which works like panama's in that a scope can't be closed until any scopes with dependencies on it are.

cc @karllessard @Craigacp @saudet

rnett avatar Jul 16 '21 20:07 rnett

The WeakIdentityHashMap is taken from https://github.com/plume-lib/plume-util and is mostly a placeholder atm.

rnett avatar Jul 17 '21 19:07 rnett

I'm planning on doing the same thing as discussed in https://inside.java/2021/09/16/finalizing-the-foreign-apis/: registering all scopes w/ the cleaner, but also allowing them to be closed manually.

rnett avatar Sep 16 '21 20:09 rnett

I'm planning on doing the same thing as discussed in https://inside.java/2021/09/16/finalizing-the-foreign-apis/: registering all scopes w/ the cleaner, but also allowing them to be closed manually.

That's fine, as long as there is a way to disable this behavior, see issue #313.

saudet avatar Sep 16 '21 23:09 saudet

I'm also going to add some way to add "on added" and "on removed" handlers at a scope level, to support stuff like the new gradient API's memory management (see the "Some details on memory management" section above here).

rnett avatar Sep 24 '21 17:09 rnett