Interrupting an Akka thread under certain conditions to avoid memory consumption

Hope this question does make sense but been recently playing with Akka and bugging myself with something that seems trivial at first but may conflict the whole system.

What I’m trying to solve is that whenever an actor makes a call to another actor with a given timeout I’m 100% sure that if the timeout is triggered the response that is being computed underneath and no longer to be consumed won’t fit in memory and crash the whole system.

Would it be safe to, in case of a timeout, notify the underneath actor thread to stop that computation and all the subsequent calls? I will put some pseudocode to illustrate better.

        Patterns.ask(...)
            .onComplete(new OnComplete<Object> {
            @Override
            public void onComplete(Throwable failure, Object success) throws Throwable {
                // Interrupt Future<Object> (Patterns.ask() thread) in here?
            }
        }, ...);

You should pretty much never drop down to the underlying thread APIs as that will require detailed understanding of the Akka internals, instead I’d recommend that you aim to model your requirements with actors and messages.

One pattern would be to put a timeout/deadline in the request command, then make the processing actor look at that timeout in its processing loop and cancel processing if it has taken too long time.

Another common pattern would be to split the processing up in smaller parts in the worker actor and send a continue message to itself allowing processing of potential messages from other actors inbetween, like a cancel work command for example. This allows for more dynamic canceling of work as other actors can decide when they send the cancel command.

1 Like

Thanks a lot for replying!

Any sources I can check those patterns on or any example? The first one you mentioned seems like the most suitable one in my case, since in the second one it’s impossible to split the incoming load in chunks, or at least make it conscious of what’s coming.

Also, how can for example a new thread being instantiated (from a single pool executor) within a message handler affect Akka performance or internals? Any specific docs I can check on this?

It’d actually be pretty much the same, but perhaps the messaging style is less obvious: you’d have to find a place in your processing where you check if you should abort, either with a conditional or by storing progress so far and all needed data from the request, and sending an internal message to self saying continue from where I left it.

I don’t know any good examples to point you to from the top of my head I’m afraid.

Not sure I understand the additional follow up question about threads, please clarify a bit what you are asking.