Scala Actors -Terrance Dsilva.  Thankfully, Scala offers a reasonable, flexible approach to concurrency  Actors aren’t a concept unique to Scala.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

More about functions Plus a few random things. 2 Tail recursion A function is said to be tail recursive if the recursive call is the very last thing it.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Loops in LabVIEW (while,for and case)
PZ11B Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ11B - Parallel execution Programming Language Design.
Remote Procedure Call in SR Programming Language By Tze-Kin Tsang 3/20/2000.
Concurrency CS 510: Programming Languages David Walker.
Scripting Languages For Virtual Worlds. Outline Necessary Features Classes, Prototypes, and Mixins Static vs. Dynamic Typing Concurrency Versioning Distribution.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
HAS. Patterns The use of patterns is essentially the reuse of well established good ideas. A pattern is a named well understood good solution to a common.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
Chapter 10 Classes Continued
16-Aug-15 Actors Concurrency made easy(-er). 2 The actor model Most of the problems with concurrency--from deadlocks to data corruption-- result from.
Starting Chapter 4 Starting. 1 Course Outline* Covered in first half until Dr. Li takes over. JAVA and OO: Review what is Object Oriented Programming.
CSE 486/586 CSE 486/586 Distributed Systems PA Best Practices Steve Ko Computer Sciences and Engineering University at Buffalo.
Programming Network Servers Topic 6, Chapters 21, 22 Network Programming Kansas State University at Salina.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Jun 16, 2014IAT 2651 Debugging. Dialectical Materialism  Dialectical materialism is a strand of Marxism, synthesizing Hegel's dialectics, which proposes.
Lists in Python.
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
12/1/98 COP 4020 Programming Languages Parallel Programming in Ada and Java Gregory A. Riccardi Department of Computer Science Florida State University.
Specialized Sending and Receiving David Monismith CS599 Based upon notes from Chapter 3 of the MPI 3.0 Standard
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Problems with Send and Receive Low level –programmer is engaged in I/O –server often not modular –takes 2 calls to get what you want (send, followed by.
1 Causal-Consistent Reversible Debugging Ivan Lanese Focus research group Computer Science and Engineering Department University of Bologna/INRIA Bologna,
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
1 Lecture 5 (part2) : “Interprocess communication” n reasons for process cooperation n types of message passing n direct and indirect message passing n.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Programming Paradigms for Concurrency Pavol Cerny Vasu Singh Thomas Wies Part III – Message Passing Concurrency.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Concurrent Programming and Threads Threads Blocking a User Interface.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 8: Modelling Interactions and Behaviour UML Sequence Diagram.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
PZ12B Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ12B - Synchronization and semaphores Programming Language.
Synchronization and semaphores Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Chapter 7 - Interprocess Communication Patterns
Observations so far…. In general… There are two ways to design a software system –Centralized control One “driver” function that contains the entire algorithm.
On Implementing High Level Concurrency in Java G Stewart von Itzstein Mark Jasiunas University of South Australia.
1 Parallel execution Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Object-Oriented Design Concepts University of Sunderland.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
OOP Basics Classes & Methods (c) IDMS/SQL News
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 An SDL Tutorial Two primary elements: –Structure –Identifies the various components of the system, and the communication paths among them. –Components:
CHAPTER 6 Threads, Handlers, and Programmatic Movement.
Functional Processing of Collections (Advanced) 6.0.
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
Error Handling Summary of the next few pages: Error Handling Cursors.
Functions Inputs Output
Concurrency made easy(-er)
For Loops October 12, 2017.
Learning to Program in Python
Concurrency made easy(-er)
Concurrency made easy(-er)
Concurrency made easy(-er)
Object Oriented Design & Analysis
Concurrency made easy(-er)
Parallel execution Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Synchronization and semaphores
Design Patterns: A Place to get Design Ideas
Threads and concurrency / Safety
Presentation transcript:

Scala Actors -Terrance Dsilva

 Thankfully, Scala offers a reasonable, flexible approach to concurrency  Actors aren’t a concept unique to Scala. Actors, originally intended for use in Artificial Intelligence research, were first put forth in 1973 (see [Hewitt1973] and [Agha1987]). [Hewitt1973][Agha1987]  Actors have appeared in a number of programming languages, most notably in Erlang and Io.

 Actors encapsulate state and behavior (like objects)  Actors are logically active (unlike most objects)  Actors communicate through asynchronous message passing (nonblocking send, locking receive)

 Actor is an object that receives messages and takes action on those messages.  The order in which messages arrive is unimportant to an Actor, though some Actor implementations (such as Scala’s) queue messages in order.  An Actor might handle a message internally, or it might send a message to another Actor, or it might create another Actor to take action based on the message.

 Actors don’t enforce a sequence or ordering to their actions. This inherent eschewing of sequentiality, coupled with independence from shared global state, allow Actors to do their work in parallel.  Actors are a very high-level abstraction.  Enough theory. Let’s see Actors in action.

 Actors in Scala are objects that inherit from scala.actors.Actor. import scala.actors.Actor class Sample extends Actor { def test() { println(“Hello.") } val objectsample = new Sample objectsample.start  Actor defined in this way must be both instantiated and started, similar to how threads are handled in Java. It must also implement the abstract method act, which returns Unit.

 The scala.actors package contains a factory method for creating Actors that avoids much of the setup in the above example. We can import this method and other convenience methods from scala.actors.Actors._. import scala.actors.Actor import scala.actors.Actor._ val paulNewman = actor { println("To be an actor, you have to be a child.") }  While a subclass that extends the Actor class must define act in order to be concrete, a factory-produced Actor has no such limitation. In this shorter example, the body of the method passed to actor is effectively promoted to the act method from our first example

Actors can receive any sort of object as a message, from strings of text to numeric types to whatever classes. An Actor should only act on messages of familiar types; a pattern match on the class and/or contents of a message is good defensive programming, and increases the readability of Actor code. val Test1 = actor { loop { receive { case s: String => println("I got a String: " + s) case i: Int => println("I got an Int: " + i.toString) } Test1 ! "hi there" Test2 ! 23

 The example prints  I got a String: hi there  I got an Int: 23  The body of Test1 is a receive method wrapped in a loop. loop is essentially a nice shortcut for while(true); it does whatever is inside its block repeatedly. receive blocks until it gets a message of a type that will satisfy one of its internal pattern matching cases.  The final lines of this example demonstrate use of the ! (exclamation point, or bang) method to send messages to our Actor. If you’ve ever seen Actors in Erlang, you’ll find this syntax familiar.  The Actor is always on the left-hand side of the bang, and the message being sent to said Actor is always on the right

 Every Actor has a mailbox in which messages sent to that Actor are queued. import scala.actors.Actor import scala.actors.Actor._ val count = actor { loop { react { case "how many?" => { println(mailboxSize.toString + " number is mailbox.") } count ! 1 count ! 2 count! 3

 This example produces the following output. 3 messages in my mailbox.  Tip If you see an Actor’s mailbox size ballooning unexpectedly, you’re probably sending messages of a type that the Actor doesn’t know about. Include a catchall case (_) when pattern matching received messages to find out what’s harassing your Actors.

In order to get the most out of Actors, there are few things to remember. First off, note that there are several methods you can use to get different types of behavior out of your Actors. The table below should help clarify when to use each method. MethodReturnsDescription actUnitAbstract, top-level method for an Actor. Typically contains one of the following methods inside it. receiveResult of processing messageBlocks until a message of matched type is received. receiveWithinResult of processing messageLike receive but unblocks after specified number of milliseconds. reactNothingRequires less overhead (threads) than receive. reactWithinNothingLike react but unblocks after specified number of milliseconds. Table 9.1. Actor Methods

 To send a message, use actor ! message The thread sending the message keeps going--it doesn’t wait for a response  To receive a message (in an Actor), use either receive {...} or react {...} -Both receive and react block until they get a message that they recognize (with case) -When receive finishes, it keeps its Thread -Statements following receive{...} +will then be executed -When react finishes, it returns its Thread to the thread pool -Statements following the react{...} statement will not be executed -The Actor’s variable stack will not be retained -This (usually) makes react more efficient than receive  Hence: Prefer react to receive, but be aware of its limitations

 Martin Odersky gives some rules for using Actors effectively  Actors should not block while processing a message  Communicate with actors only via messages  Scala does not prevent actors from sharing state, so it’s (unfortunately) very easy to do  Prefer immutable messages  Mutable data in a message is shared state  Make messages self-contained  When you get a response from an actor, it may not be obvious what is being responded to  If the request is immutable, it’s very inexpensive to include the request as part of the response  The use of case classes often makes messages more readable