开发者

Scala folding using Akka

I implemented in Java what I called a "foldable queue", i.e., a LinkedBlockingQueue used by an ExecutorService. The idea is that each task as a unique id that if is in the queue while another task is submitted via that same id, it is not added to the queue. The Java code looks like this:

public final class FoldablePricingQueue extends LinkedBlockingQueue<Runnable> {
    @Override
    public boolean offer(final Runnable runnable) {
        if (contains(runnable)) {
            return true; // rejected, but true not to throw an exception
        } else {
     开发者_StackOverflow       return super.offer(runnable);
        }
    }
}

Threads have to be pre-started but this is a minor detail. I have an Abstract class that implements Runnable that takes a unique id... this is the one passed in

I would like to implement the same logic using Scala and Akka (Actors). I would need to have access to the mailbox, and I think I would need to override the ! method and check the mailbox for the event.. has anyone done this before?


This is exactly how the Akka mailbox works. The Akka mailbox can only exist once in the task-queue.

Look at:

https://github.com/jboner/akka/blob/master/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala#L143

https://github.com/jboner/akka/blob/master/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala#L198

Very cheaply implemented using an atomic boolean, so no need to traverse the queue.

Also, by the way, your Queue in Java is broken since it doesn't override put, add or offer(E, long, TimeUnit).


Maybe you could do that with two actors. A facade one and a worker one. Clients send jobs to facade. Facade forwards then to worker, and remember them in its internal state, a Set queuedJobs. When it receives a job that is queued, it just discard it. Each time the worker starts processing a job (or completes it, whichever suits you), it sends a StartingOn(job) message to facade, which removes it from queuedJobs.


The proposed design doesn't make sense. The closest thing to a Runnable would be an Actor. Sure, you can keep them in a list, and not add them if they are already there. Such lists are kept by routing actors, which can be created from ready parts provided by Akka, or from a basic actor using the forward method.

You can't look into another actor's mailbox, and overriding ! makes no sense. What you do is you send all your messages to a routing actor, and that routing actor forwards them to a proper destination.

Naturally, since it receives these messages, it can do any logic at that point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜