public
Last active

Swing Actors using Akka

  • Download Gist
swingactors.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
// ©2012 Viktor Klang
 
package akka.klang
 
import akka.dispatch.{ DispatcherPrerequisites, ExecutorServiceFactory, ExecutorServiceConfigurator }
import com.typesafe.config.Config
import java.util.concurrent.{ ExecutorService, AbstractExecutorService, ThreadFactory, TimeUnit }
import java.util.Collections
import javax.swing.SwingUtilities
 
// First we wrap invokeLater as an ExecutorService
object SwingExecutorService extends AbstractExecutorService {
def execute(command: Runnable) = SwingUtilities.invokeLater(command)
def shutdown(): Unit = ()
def shutdownNow() = Collections.emptyList[Runnable]
def isShutdown = false
def isTerminated = false
def awaitTermination(l: Long, timeUnit: TimeUnit) = true
}
 
// Then we create an ExecutorServiceConfigurator so that Akka can use our SwingExecutorService for the dispatchers
class SwingEventThreadExecutorServiceConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends ExecutorServiceConfigurator(config, prerequisites) {
private val f = new ExecutorServiceFactory { def createExecutorService: ExecutorService = SwingExecutorService }
def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = f
}
 
// Then we simply need to create a dispatcher configuration in our application.conf
 
swing-dispatcher {
type = "Dispatcher"
executor = "akka.klang.SwingEventThreadExecutorServiceConfigurator"
throughput = 1
}
 
// After that we just create the GUI Actors with a Props with the correct dispatcher set:
 
val frameActor = context.actorOf(Props[FrameActor].withDispatcher("swing-dispatcher"), "frame-actor")
 
// Done! Now all messages processed by "frameActor" will be executed by the Swing Event Dispatch Thread, enjoy!

Thank you. I have extended this gist to include JavaFX actors as suggested by this stackoverflow answer. It can be found here.

Could you explain where the g.draw() calls go? Does the frameActor gets created inside another actor? Thanks.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.