- more style related cleanup

This commit is contained in:
Peter Veentjer 2011-05-18 08:37:58 +02:00
parent 61fb04affb
commit e7d1eaf15c
6 changed files with 501 additions and 384 deletions

View file

@ -16,22 +16,24 @@ import akka.actor._
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
final case class MessageInvocation(val receiver: ActorRef,
val message: Any,
val sender: Option[ActorRef],
val senderFuture: Option[CompletableFuture[Any]]) {
final case class MessageInvocation(receiver: ActorRef,
message: Any,
sender: Option[ActorRef],
senderFuture: Option[CompletableFuture[Any]]) {
if (receiver eq null) throw new IllegalArgumentException("Receiver can't be null")
def invoke = try {
receiver.invoke(this)
} catch {
case e: NullPointerException => throw new ActorInitializationException(
"Don't call 'self ! message' in the Actor's constructor (in Scala this means in the body of the class).")
def invoke() {
try {
receiver.invoke(this)
} catch {
case e: NullPointerException => throw new ActorInitializationException(
"Don't call 'self ! message' in the Actor's constructor (in Scala this means in the body of the class).")
}
}
}
final case class FutureInvocation[T](future: CompletableFuture[T], function: () => T, cleanup: () => Unit) extends Runnable {
def run = {
def run() {
future complete (try {
Right(function())
} catch {
@ -46,22 +48,23 @@ final case class FutureInvocation[T](future: CompletableFuture[T], function: ()
object MessageDispatcher {
val UNSCHEDULED = 0
val SCHEDULED = 1
val SCHEDULED = 1
val RESCHEDULED = 2
implicit def defaultGlobalDispatcher = Dispatchers.defaultGlobalDispatcher
}
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait MessageDispatcher {
import MessageDispatcher._
protected val uuids = new ConcurrentSkipListSet[Uuid]
protected val uuids = new ConcurrentSkipListSet[Uuid]
protected val futures = new AtomicLong(0L)
protected val guard = new ReentrantGuard
protected val active = new Switch(false)
protected val guard = new ReentrantGuard
protected val active = new Switch(false)
private var shutdownSchedule = UNSCHEDULED //This can be non-volatile since it is protected by guard withGuard
@ -73,18 +76,24 @@ trait MessageDispatcher {
/**
* Attaches the specified actorRef to this dispatcher
*/
final def attach(actorRef: ActorRef): Unit = guard withGuard {
register(actorRef)
final def attach(actorRef: ActorRef) {
guard withGuard {
register(actorRef)
}
}
/**
* Detaches the specified actorRef from this dispatcher
*/
final def detach(actorRef: ActorRef): Unit = guard withGuard {
unregister(actorRef)
final def detach(actorRef: ActorRef) {
guard withGuard {
unregister(actorRef)
}
}
private[akka] final def dispatchMessage(invocation: MessageInvocation): Unit = dispatch(invocation)
private[akka] final def dispatchMessage(invocation: MessageInvocation) {
dispatch(invocation)
}
private[akka] final def dispatchFuture[T](block: () => T, timeout: Long): Future[T] = {
futures.getAndIncrement()
@ -92,7 +101,11 @@ trait MessageDispatcher {
val future = new DefaultCompletableFuture[T](timeout)
if (active.isOff)
guard withGuard { active.switchOn { start } }
guard withGuard {
active.switchOn {
start()
}
}
executeFuture(FutureInvocation[T](future, block, futureCleanup))
future
@ -104,7 +117,7 @@ trait MessageDispatcher {
}
private val futureCleanup: () => Unit =
() => if (futures.decrementAndGet() == 0) {
() => if (futures.decrementAndGet() == 0) {
guard withGuard {
if (futures.get == 0 && uuids.isEmpty) {
shutdownSchedule match {
@ -126,7 +139,7 @@ trait MessageDispatcher {
uuids add actorRef.uuid
if (active.isOff) {
active.switchOn {
start
start()
}
}
}
@ -134,7 +147,7 @@ trait MessageDispatcher {
private[akka] def unregister(actorRef: ActorRef) = {
if (uuids remove actorRef.uuid) {
actorRef.mailbox = null
if (uuids.isEmpty && futures.get == 0){
if (uuids.isEmpty && futures.get == 0) {
shutdownSchedule match {
case UNSCHEDULED =>
shutdownSchedule = SCHEDULED
@ -150,31 +163,33 @@ trait MessageDispatcher {
/**
* Traverses the list of actors (uuids) currently being attached to this dispatcher and stops those actors
*/
def stopAllAttachedActors {
def stopAllAttachedActors() {
val i = uuids.iterator
while (i.hasNext()) {
val uuid = i.next()
Actor.registry.local.actorFor(uuid) match {
case Some(actor) => actor.stop()
case None => {}
case None => {}
}
}
}
private val shutdownAction = new Runnable {
def run = guard withGuard {
shutdownSchedule match {
case RESCHEDULED =>
shutdownSchedule = SCHEDULED
Scheduler.scheduleOnce(this, timeoutMs, TimeUnit.MILLISECONDS)
case SCHEDULED =>
if (uuids.isEmpty && futures.get == 0) {
active switchOff {
shutdown // shut down in the dispatcher's references is zero
def run() {
guard withGuard {
shutdownSchedule match {
case RESCHEDULED =>
shutdownSchedule = SCHEDULED
Scheduler.scheduleOnce(this, timeoutMs, TimeUnit.MILLISECONDS)
case SCHEDULED =>
if (uuids.isEmpty && futures.get == 0) {
active switchOff {
shutdown() // shut down in the dispatcher's references is zero
}
}
}
shutdownSchedule = UNSCHEDULED
case UNSCHEDULED => //Do nothing
shutdownSchedule = UNSCHEDULED
case UNSCHEDULED => //Do nothing
}
}
}
}
@ -188,29 +203,29 @@ trait MessageDispatcher {
/**
* After the call to this method, the dispatcher mustn't begin any new message processing for the specified reference
*/
def suspend(actorRef: ActorRef): Unit
def suspend(actorRef: ActorRef)
/*
* After the call to this method, the dispatcher must begin any new message processing for the specified reference
*/
def resume(actorRef: ActorRef): Unit
def resume(actorRef: ActorRef)
/**
* Will be called when the dispatcher is to queue an invocation for execution
*/
private[akka] def dispatch(invocation: MessageInvocation): Unit
private[akka] def dispatch(invocation: MessageInvocation)
private[akka] def executeFuture(invocation: FutureInvocation[_]): Unit
private[akka] def executeFuture(invocation: FutureInvocation[_])
/**
* Called one time every time an actor is attached to this dispatcher and this dispatcher was previously shutdown
*/
private[akka] def start(): Unit
private[akka] def start()
/**
* Called one time every time an actor is detached from this dispatcher and this dispatcher has no actors left attached
*/
private[akka] def shutdown(): Unit
private[akka] def shutdown()
/**
* Returns the size of the mailbox for the specified actor
@ -235,25 +250,30 @@ abstract class MessageDispatcherConfigurator {
def mailboxType(config: Configuration): MailboxType = {
val capacity = config.getInt("mailbox-capacity", Dispatchers.MAILBOX_CAPACITY)
if (capacity < 1) UnboundedMailbox()
else BoundedMailbox(capacity, Duration(config.getInt("mailbox-push-timeout-time", Dispatchers.MAILBOX_PUSH_TIME_OUT.toMillis.toInt), TIME_UNIT))
else {
val duration = Duration(
config.getInt("mailbox-push-timeout-time", Dispatchers.MAILBOX_PUSH_TIME_OUT.toMillis.toInt),
TIME_UNIT)
BoundedMailbox(capacity, duration)
}
}
def configureThreadPool(config: Configuration, createDispatcher: => (ThreadPoolConfig) => MessageDispatcher): ThreadPoolConfigDispatcherBuilder = {
import ThreadPoolConfigDispatcherBuilder.conf_?
//Apply the following options to the config if they are present in the config
ThreadPoolConfigDispatcherBuilder(createDispatcher,ThreadPoolConfig()).configure(
conf_?(config getInt "keep-alive-time" )(time => _.setKeepAliveTime(Duration(time, TIME_UNIT))),
ThreadPoolConfigDispatcherBuilder(createDispatcher, ThreadPoolConfig()).configure(
conf_?(config getInt "keep-alive-time")(time => _.setKeepAliveTime(Duration(time, TIME_UNIT))),
conf_?(config getDouble "core-pool-size-factor")(factor => _.setCorePoolSizeFromFactor(factor)),
conf_?(config getDouble "max-pool-size-factor" )(factor => _.setMaxPoolSizeFromFactor(factor)),
conf_?(config getInt "executor-bounds" )(bounds => _.setExecutorBounds(bounds)),
conf_?(config getBool "allow-core-timeout" )(allow => _.setAllowCoreThreadTimeout(allow)),
conf_?(config getDouble "max-pool-size-factor")(factor => _.setMaxPoolSizeFromFactor(factor)),
conf_?(config getInt "executor-bounds")(bounds => _.setExecutorBounds(bounds)),
conf_?(config getBool "allow-core-timeout")(allow => _.setAllowCoreThreadTimeout(allow)),
conf_?(config getString "rejection-policy" map {
case "abort" => new AbortPolicy()
case "caller-runs" => new CallerRunsPolicy()
case "abort" => new AbortPolicy()
case "caller-runs" => new CallerRunsPolicy()
case "discard-oldest" => new DiscardOldestPolicy()
case "discard" => new DiscardPolicy()
case x => throw new IllegalArgumentException("[%s] is not a valid rejectionPolicy!" format x)
case "discard" => new DiscardPolicy()
case x => throw new IllegalArgumentException("[%s] is not a valid rejectionPolicy!" format x)
})(policy => _.setRejectionPolicy(policy)))
}
}