Interesting example: actor-like model using virtual threads and dynamic proxies

Paul Bjorkstrand paul.bjorkstrand at gmail.com
Sun Nov 28 00:45:43 UTC 2021


Playing with virtual threads today, I wondered how easy it would be to use
virtual threads to create an actor-like model, but without sacrificing a
simple Java API. Pulling from my memory, I thought "hey, why not dynamic
proxies?"

It went smoothly, up until I started trying to have one actor call another
actor. When having one actor call _itself_, but not using "this", it
deadlocked.

It was a little tricky to understand what was going on at first. Once I
found what the issue was, it made a lot of sense why it occurred.

I was able to fix it and get it working, and here is the result, in a gist:

https://gist.github.com/paul-bjorkstrand/8854b1346df290a60ba767977aeaf6e2

This gives me hope that creating actor models will not require a more
cumbersome message passing model. I think this will make creating actor
systems appealing, at least to people like me :-).

I remember attempting something like this using thread pools before, and
ran into the same deadlocking issue. At that time, I did not find a
solution, and abandoned the effort. With virtual threads, since they _are_
threads, I was able to do a simple == test to bypass the scheduling (no
need to schedule on the actor's thread if we are already on the actor's
thread).

While this is not a perfect implementation, it was a lot of fun to build
and troubleshoot.

-Paul


More information about the loom-dev mailing list