Cancellation with finalization

Spencer Baugh sbaugh at catern.com
Wed Jan 13 05:21:49 UTC 2021


Hi loom-dev,

I've followed with great interest the development of Project Loom,
even as a bystander who does not frequently program in Java. The use
of delimited continuations to provide normal synchronous programming,
without forcing users to annotate functions or call-sites with
asynchronous effects, seems like the best way forward for many
imperative languages. I've worked on similar things myself.[1]

I have an idea which maybe you've considered before, and I'm curious
to know if you've encountered any similar concepts.  If this is
inappropriate for this list please let me know.

It's often desirable to be able to cancel an operation. For example, a
worker thread might receive some request with some parameters from
another thread and queue it to be performed later; at some point
before the operation is complete and the result is returned to the
requester, the request (and the result) might become irrelevant; in
such a situation, the result can be discarded, and the worker thread
would be notified in some way so that it can avoid expending resources
on actually performing the operation (if it hasn't yet been
unavoidably started, or can still be interrupted).

One can conceptualize the original request as being accompanied by a
result-continuation, corresponding to the original requesting thread,
which the worker thread will call with the result.

In that model, cancellation could be implemented with weak references
and a finalizer: If the result-continuation is referenced weakly, then
if the garbage collector begins to consider the continuation garbage,
a finalizer can notify the worker thread that the request has been
cancelled, and the worker thread can discard the result if and when it
sees the reference to the result-continuation has already been
cleared.

Cancellation of an operation, then, would happen if and only if the GC
considered the original thread requesting the operation to be garbage.
For example, perhaps if a thread was maintaining some specific object,
that object would have the only reference to that thread; then if the
object became garbage, the thread would too, and whatever operation
the thread is currently blocked in (if any) would be cancelled.

Finalizers, of course, are scary, so this is probably unrealistic, but
it replaces two features with one, which is nice.

Have you ever encountered or considered such ideas before?

Either way, thanks for working on Project Loom!

[1]: https://github.com/catern/rsyscall/blob/master/python/dneio/__init__.py


More information about the loom-dev mailing list