2009-07-06 23:45:15 +02:00
|
|
|
/**
|
|
|
|
|
* Copyright (C) 2009 Scalable Solutions.
|
|
|
|
|
*/
|
|
|
|
|
|
2009-10-08 19:01:04 +02:00
|
|
|
package se.scalablesolutions.akka.dispatch
|
2009-07-06 23:45:15 +02:00
|
|
|
|
|
|
|
|
import java.util.concurrent.LinkedBlockingQueue
|
|
|
|
|
import java.util.Queue
|
2009-08-11 12:16:50 +02:00
|
|
|
|
2009-10-14 12:59:05 +02:00
|
|
|
import se.scalablesolutions.akka.actor.{Actor, ActorMessageInvoker}
|
2009-07-06 23:45:15 +02:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Dedicates a unique thread for each actor passed in as reference. Served through its messageQueue.
|
2009-10-08 19:01:04 +02:00
|
|
|
*
|
2009-07-06 23:45:15 +02:00
|
|
|
* @author <a href="http://jonasboner.com">Jonas Bonér</a>
|
|
|
|
|
*/
|
2009-10-08 19:01:04 +02:00
|
|
|
class ThreadBasedDispatcher private[akka] (val name: String, val messageHandler: MessageInvoker)
|
|
|
|
|
extends MessageDispatcher {
|
|
|
|
|
|
2009-08-11 12:16:50 +02:00
|
|
|
def this(actor: Actor) = this(actor.getClass.getName, new ActorMessageInvoker(actor))
|
2009-07-06 23:45:15 +02:00
|
|
|
|
2009-08-11 12:16:50 +02:00
|
|
|
private val queue = new BlockingMessageQueue(name)
|
2009-07-06 23:45:15 +02:00
|
|
|
private var selectorThread: Thread = _
|
|
|
|
|
@volatile private var active: Boolean = false
|
|
|
|
|
|
2009-12-11 06:44:59 +01:00
|
|
|
def dispatch(invocation: MessageInvocation) = queue.append(invocation)
|
|
|
|
|
|
2009-07-06 23:45:15 +02:00
|
|
|
def start = if (!active) {
|
|
|
|
|
active = true
|
|
|
|
|
selectorThread = new Thread {
|
|
|
|
|
override def run = {
|
|
|
|
|
while (active) {
|
|
|
|
|
try {
|
|
|
|
|
messageHandler.invoke(queue.take)
|
|
|
|
|
} catch { case e: InterruptedException => active = false }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
selectorThread.start
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def shutdown = if (active) {
|
|
|
|
|
active = false
|
|
|
|
|
selectorThread.interrupt
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2009-08-11 12:16:50 +02:00
|
|
|
class BlockingMessageQueue(name: String) extends MessageQueue {
|
2009-12-11 16:37:44 +01:00
|
|
|
// FIXME: configure the LinkedBlockingQueue in BlockingMessageQueue, use a Builder like in the ReactorBasedThreadPoolEventDrivenDispatcher
|
2009-07-06 23:45:15 +02:00
|
|
|
private val queue = new LinkedBlockingQueue[MessageInvocation]
|
2009-12-11 06:44:59 +01:00
|
|
|
def append(invocation: MessageInvocation) = queue.put(invocation)
|
2009-07-06 23:45:15 +02:00
|
|
|
def take: MessageInvocation = queue.take
|
|
|
|
|
def read(destination: Queue[MessageInvocation]) = throw new UnsupportedOperationException
|
|
|
|
|
def interrupt = throw new UnsupportedOperationException
|
2009-08-11 12:16:50 +02:00
|
|
|
}
|