alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (OrderedExecutionContext.scala)

This example Play Framework source code file (OrderedExecutionContext.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

actor, actorsystem, api, concurrent, core, executioncontext, failure, int, long, mvc, orderedexecutioncontext, play, play framework, runactor, runnable, throwable

The OrderedExecutionContext.scala Play Framework example source code

/*
 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
 */
package play.core.j

import akka.actor.{ Actor, ActorSystem, Props }
import play.api.Logger
import play.mvc.Http
import scala.concurrent.ExecutionContext

/**
 * Executes work in a fixed-sized pool of actors. If an Http.Context is associated
 * with the current thread then that id will be used to dispatch work to the same
 * actor every time, resulting in ordered execution of work for that context.
 *
 * The ExecutionContext preserves the execution behaviour of F.Promise from Play.
 */
class OrderedExecutionContext(actorSystem: ActorSystem, size: Int) extends ExecutionContext {
  private val actors = Array.fill(size)(actorSystem.actorOf(Props[OrderedExecutionContext.RunActor]))

  def execute(runnable: Runnable) = {
    val httpContext = Http.Context.current.get()
    val id: Long = if (httpContext == null) 0L else httpContext.id()
    val actor = actors((id % size).toInt)
    actor ! runnable
  }

  def reportFailure(t: Throwable) = Logger.error("Failure in OrderedExecutionContext", t)
}

object OrderedExecutionContext {
  /**
   * Used by the OrderedExecutionContext to run work in an actor.
   */
  class RunActor extends Actor {
    def receive = {
      case runnable: Runnable => runnable.run()
    }
  }
}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework OrderedExecutionContext.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.