Actors That Unify Threads and Events ... In this paper we present a unification of thread-based and event-based actors. An ..... In the process, event han-.
Jul 29, 2014 - ABSTRACT. Scala supports actors and message passing with the Akka library. Though Scala is statically typ
scoped asynchronous code def after[T](delay: Long, ... timer.schedule(new TimerTask { def run(): Unit .... Async is ther
actors and threads which does not violate the properties of the event-driven actor ...... Timer class is typically used to schedule tasks for execution at a later point in time as .... For example, Jython allows Python classes to subclass Java classe
Objects can be created ex-nihilo, by cloning or by instantiating objects. In- stantiating an object is done by sending it the message new, which creates a shallow.
software components with static data and hard references, resulting in a ... aspect-oriented programming (indeed, the fr
Say, we want a log of every symbol and type creation, written to standard output. .... XML data are trees which need to
Here, matrix is assumed to be of type Array[Array[int]], using Scala's. Array class (explained .... required services. N
... into practical object- oriented programming languages. .... We assume that object A owns object B. This means that r
public class Download { public static void main(String[] args) {. // actor initializations. IDownloadManager manager = new actor DownloadManager(); for (int i = 0; ...
Jul 29, 2014 - ences with a simple application, a supervised calculator. (Section 2). . We review the Akka API, and pres
Oct 17, 2011 - three different domain-specific languages in Scala. ... hosting an up-to-date version of the Scala IDE for Eclipse based on .... sions to a context-free grammar (anbn) can be enforced in the type system: ..... only contains the name of
10 Jul 2010 ... DRAFT. Playground for LINQ Expression Trees c Miguel Garcia, LAMP,. École
Polytechnique Fédérale de Lausanne (EPFL).
example, component-assembly code must ensure that a user- interface .... Cleanup" icon="icons/cleanup.gif" tooltip="Clea
[8] P. Caspi, D. Pilaud, N. Halbwachs, and J. A. Plaice. LUSTRE: a declarative language for programming synchronous syst
which processes do not recover after a crash) that specifications of group commu- .... less, some protocols need to get different kinds of data via this single handler. ... the message's sequence of headers drives its processing in the composition. .
Nov 9, 2004 - Sean McDirmid and Wilson C. Hsieh .... Locked([getBalance()],[Accnt.lock]) specifies that the lock Accnt.lock must be acquired around get-.
Modern network services present software engineers with a number of design .... Thread synchronization: Non-blocking syn
ming models for building massively concurrent network services: ... 1. Introduction. Modern network services present software engineers with a num-.
Abstract. We describe a non-blocking concurrent hash trie based on shared- memory single-word compare-and-swap instructions. The hash trie supports ...
Nov 9, 2015 - 1. arXiv:1511.02917v1 [cs.CV] 9 Nov 2015 ..... lar to the RCNN object detector[9], the appearance features were extracted by feeding the ...
Recent popular languages such as Java [16] or the .NET common ... Ï-calculus and that is implemented as a library in the host language Scala [22]. Scala is a ...
Actors that Unify Threads and Events - LAMP | EPFL
Jul 6, 2007 - ... applications. â Web services. â Distributed software. â Hardware is concurrent. â Hyperthreadi
Actors that Unify Threads and Events Philipp Haller, EPFL joint work with Martin Odersky, EPFL
Implementing Concurrent Processes 1●
2●
Threadbased –
Behavior = body of designated method
–
Execution state = thread stack
–
Examples: Java threads, POSIX threads
Eventbased –
Behavior = set of event handlers
–
Execution state = object shared by handlers
–
Examples: Java Swing, TinyOS
06/07/07
Philipp Haller – Scala Actors
2/23
Threads [Ousterhout96] ●
Support multiple hardware cores (Good)
●
Behavior = sequential program (Good)
●
Heavyweight (Bad) –
High memory consumption ●
– ●
Preallocated stacks
Lock contention bottleneck
Synchronization using locks errorprone, not composable (Bad)
06/07/07
Philipp Haller – Scala Actors
3/23
Events: Remedy? [vonBehren03] ●
Lightweight (Good) –
Multiple events interleaved on single thread
–
Low memory consumption
●
Automatic synchronization (Good)
●
No hardware support (Bad)
●
Inversion of control (Bad) –
06/07/07
Behavior != sequential program
Philipp Haller – Scala Actors
4/23
Rest of this Talk ●
Programming with Actors in Scala
●
Unifying Threads and Events –
Programming Model
–
Lightweight Execution Environment
●
Composing Actors
●
Selective Communication
●
Experimental Results
06/07/07
Philipp Haller – Scala Actors
5/23
Actors ●
●
●
●
Model of concurrent processes introduced by Hewitt and Agha Upon reception of a message, an actor may –
send messages to other actors
–
create new actors
–
change its behavior/state
Most popular implementation: Erlang But: No widespread adoption in languages for standard VMs (e.g. JVM, CLR)
06/07/07
Philipp Haller – Scala Actors
6/23
Actors in Scala ●
●
●
Two principle operations (adopted from Erlang) actor ! message
// message send
receive { case msgpat_1 => action_1 ... case msgpat_n => action_n }
// message receive
Send is asynchronous; messages are buffered in actor's mailbox receive waits for message that matches any of
the patterns msgpat_i 06/07/07
Philipp Haller – Scala Actors
7/23
Example: Producers ●
Producers act like iterators, generate values concurrently with consumer: class InOrder(n: IntTree) extends Producer[Int] { def produceValues = traverse(n) def traverse(n: IntTree) = if (n != null) { traverse(n.left) produce(n.elem) traverse(n.right) } }
●
Methods produceValues (abstract) and produce inherited from class Producer
06/07/07
Philipp Haller – Scala Actors
8/23
Implementing Producers Producers are implemented in terms of two actors.
The producer actor runs produceValues:
1●
abstract class Producer[T] extends Iterator[T] { def produceValues: Unit def produce(x: T) { coordinator ! Some(x) } private val producer = actor { produceValues; coordinator ! None } }
06/07/07
Philipp Haller – Scala Actors
9/23
Implementing Producers (2) 2●
The coordinator actor synchronizes requests from clients and values from the producer val coordinator = actor { while (true) { receive { case Next => receive { case x: Option[_] => client ! x } } } }
Suspend in Event Mode Task Ti: ... react { case Msg(x) => // handle msg }
Exception: Worker thread: 1●
2●
try { Unwinds stack of // execute Ti }actor/worker thread catch { case _: Finishes current task SuspendActorExc => // do nothing }
def react(f: PartialFunction[Any, Unit]): Nothing = { mailbox.dequeueFirst(f.isDefinedAt) match { case None => continuation = f; suspended = true case Some(msg) => ... } throw new SuspendActorException } 06/07/07
Philipp Haller – Scala Actors
15/23
Resume in Event Mode Actor a waits for
wt executes Ti
{ case Msg(x) => // handle msg
Ti+1
}
Task Ti:
Ti+2
... a ! Msg(42) ...
Ti+2: 06/07/07
.apply(Msg(42)) Philipp Haller – Scala Actors
16/23
Thread Pool Resizing A suspended in receive { case Msg(x) =>... }
wt1
B suspended in library (e.g. wait()) wt2 T1
T1: 06/07/07
... A ! Msg(x) ...
Executing T1 would unblock wt1!
Philipp Haller – Scala Actors
17/23
Implementing Producers (3) Economize one thread in Producer by changing receive in the coordinator actor to react val coordinator = actor { loop { react { case Next => react { case x: Option[_] => client ! x } } } } 06/07/07
Philipp Haller – Scala Actors
18/23
Composing Actors ●
●
Composing eventdriven code nontrivial –
react may unwind stack at any point
–
Normal sequencing does not work
Composition operators for common uses –
a andThen b runs a followed by b
–
def loop(body: => Unit) = body andThen loop(body)
06/07/07
Philipp Haller – Scala Actors
19/23
Channels trait OutputChannel[-Msg] { def !(msg: Msg): Unit def forward(msg: Msg): Unit } trait InputChannel[+Msg] { receive[R](f: PartialFunction[Msg, R]): R react(f: PartialFunction[Msg, Unit]): Nothing ... } class Channel[Msg] extends InputChannel[Msg] with OutputChannel[Msg] trait Actor extends OutputChannel[Any] { ... } 06/07/07
Philipp Haller – Scala Actors
20/23
Selective Communication ●
Generalize receive/react: receive { case DataCh ! data => ... case CtrlCh ! cmd => ... }
●
Composing alternatives using orElse: receive { case DataCh ! data => ... case CtrlCh ! cmd => ... } orElse super.reactions
06/07/07
Philipp Haller – Scala Actors
21/23
Experimental Results Number of token passes per second in ring of processes.
06/07/07
Philipp Haller – Scala Actors
22/23
Conclusion ●
●
Threads and events can be unified under an abstraction of actors receive/react allows programmers to tradeoff
efficiency for flexibility ●
●
Implemented in Scala Actors library ( http://www.scala-lang.org/) Realworld usage: lift web framework
06/07/07
Philipp Haller – Scala Actors
23/23
Thread Pool Resizing (2) (cf. SEDA [Welsh01]) ●
●
●
Sample task queue Add thread when queue length exceeds threshold (up to max. number of threads) Remove thread when idle for specified period of time
06/07/07
Philipp Haller – Scala Actors
24/23
Experimental Results (2)
●
●
Micro benchmarks run on 4way dualcore Opteron machine (8 cores total) Compared to Doug Lea's FJTask framework for Java
06/07/07
Philipp Haller – Scala Actors
25/23
Programming with Events def httpFetch(queryURL: String) = { val req = new XmlHttpRequest req.addOnReadyStateChangedListener(new PropertyChangeListener() { override def propertyChange(evt: PropertyChangeEvent) { if (evt.getNewValue() == ReadyState.LOADED) { val response = req.getResponseText() httpParseResponse(response) } } }) try { req.open(Method.GET, new URL(queryURL)) req.send() } catch { case e: Throwable => ... } }
Typical asynchronous HTTP document fetch
06/07/07
Philipp Haller – Scala Actors
26/23
Inversion of Control Client
Server
val res = evt...
06/07/07
Philipp Haller – Scala Actors
27/23
Problems of Inversion of Control ●
Hard to understand controlflow –
●
●
reconstruct entire callgraph
Manual stack management –
handler code not defined where event is handled
–
local variables, parameters etc. not accessible
Managing resources (files, sockets) becomes even harder –