Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt task in Scala?

As I understand Scala Actors cannot be interrupted. Suppose now that I have a task with a timeout. If the task does not finish within the timeout I should stop it.

Suppose that the task is interruptible (e.g. performs blocking i/o upon an interruptible channel). In Java I can run the task in a separate thread and interrupt the thread on timeout.

Can I do that with Scala Actors ? Should I use Java threads instead ?

like image 863
Michael Avatar asked Nov 04 '22 00:11

Michael


1 Answers

You cannot interrupt an Actor if you follow the Actor model precisely. That is: if you do not want to share. This is proposed in the How to cancel an Akka actor answer by using an AtomicBoolean for instance.

However the general answer is: you are trying to use Java threading idioms within actors. This is wrong. Rather than have a long running task, you should split your work into smaller batches.

From the Akka documentation, Actor Best Practices:

Actors should be like nice co-workers: do their job efficiently without bothering everyone else needlessly and avoid hogging resources. Translated to programming this means to process events and generate responses (or more requests) in an event-driven manner. Actors should not block (i.e. passively wait while occupying a Thread) on some external entity—which might be a lock, a network socket, etc.—unless it is unavoidable; in the latter case see below.

Can you do this with Scala Actors? No, you will run into the same issue because your problem is of conceptual nature, not related to the framework implementation.

Should you use Java Threads instead? If you want to follow the Java threading idioms, then yes: go for it. But if you want to use Actor concurrency you have to adopt a different thinking model to reap all the benefits.

like image 164
Joa Ebert Avatar answered Nov 15 '22 05:11

Joa Ebert