CMPT 435/835 Tutorial 1 Actors Model & Akka. Ahmed Abdel Moamen PhD Candidate Agents Lab

Similar documents
Akka Java Documentation

Akka. Reactive Applications made easy

Favoring Isolated Mutability The Actor Model of Concurrency. CSCI 5828: Foundations of Software Engineering Lecture 24 04/11/2012

Cover Page. The handle holds various files of this Leiden University dissertation

CS Programming Languages: Scala

Distributed Data Analytics Akka Actor Programming

[ «*< > t] open source t. Akka Essentials. Akka's actor-based, distributed, concurrent, and scalable Java applications

Targeted Test Generation for Actor Systems

Covers Scala 2.10 IN ACTION. Nilanjan Raychaudhuri. FOREWORD BY Chad Fowler MANNING

Executive Summary. It is important for a Java Programmer to understand the power and limitations of concurrent programming in Java using threads.

Akka: Simpler Concurrency, Scalability & Fault-tolerance through Actors. Jonas Bonér Scalable Solutions

}w!"#$%&'()+,-./012345<ya

Akka Java Documentation

Akka: Simpler Concurrency, Scalability & Fault-tolerance through Actors. Jonas Bonér Viktor Klang

Scaling out with Akka Actors. J. Suereth

Scaling Up & Out. Haidar Osman

Programming Paradigms for Concurrency Lecture 10 The Actor Paradigm

Philipp Wille. Beyond Scala s Standard Library

Scala Actors. Scalable Multithreading on the JVM. Philipp Haller. Ph.D. candidate Programming Methods Lab EPFL, Lausanne, Switzerland

Message-passing concurrency in Erlang

Above the Clouds: Introducing Akka. Jonas Bonér Scalable Solutions

Akka Scala Documentation

A Scalable and Reliable Message Transport Service for the ATLAS Trigger and Data Acquisition System

Concurrency. Unleash your processor(s) Václav Pech

Using the SDACK Architecture to Build a Big Data Product. Yu-hsin Yeh (Evans Ye) Apache Big Data NA 2016 Vancouver

Advantages of concurrent programs. Concurrent Programming Actors, SALSA, Coordination Abstractions. Overview of concurrent programming

Making most of Scala. Akka, Scala, Spray, Specs2; all in 50 minutes!

Remote Invocation. 1. Introduction 2. Remote Method Invocation (RMI) 3. RMI Invocation Semantics

Reactive App using Actor model & Apache Spark. Rahul Kumar Software

DISTRIBUTED OBJECTS AND REMOTE INVOCATION

!! How is a thread different from a process? !! Why are threads useful? !! How can POSIX threads be useful?

Chapter 4: Threads. Operating System Concepts. Silberschatz, Galvin and Gagne

ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I

DISTRIBUTED COMPUTER SYSTEMS

The Actor Model. Towards Better Concurrency. By: Dror Bereznitsky

Interprocess Communication

Evolution of an Apache Spark Architecture for Processing Game Data

CONCURRENCY AND THE ACTOR MODEL

Effectively Mapping Linguistic Abstractions for Message-passing Concurrency to Threads on the Java Virtual Machine

Operating Systems 2 nd semester 2016/2017. Chapter 4: Threads

Multithreaded Programming

PCPP: PRACTICAL CONCURRENT & PARALLEL PROGRAMMERING. Claus Brabrand ((( )))

Combining Concurrency Abstractions

! How is a thread different from a process? ! Why are threads useful? ! How can POSIX threads be useful?

Akka. Developing SEDA Based Applications

Processes. Process Concept

! The Process Control Block (PCB) " is included in the context,

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - III Processes. Louisiana State University. Processes. September 1 st, 2009

Microservices. Webservices with Scala (II) Microservices

Inside Broker How Broker Leverages the C++ Actor Framework (CAF)

CS 6112 (Fall 2011) Foundations of Concurrency

The do s and don ts of error handling. Joe Armstrong

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

The Overlay Socket API

simpa An Agent-Oriented Approach for Prototyping Concurrent Applications on Top of Java

Chapter 4: Processes. Process Concept. Process State

Communication Paradigms

Remote Invocation Vladimir Vlassov and Johan Montelius

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS 231 Data Structures and Algorithms, Fall 2016

High-level Parallel Programming: Scala on the JVM

Using the Actor Framework in LabVIEW

Chapter 4: Threads. Chapter 4: Threads. Overview Multicore Programming Multithreading Models Thread Libraries Implicit Threading Threading Issues

Problems with Concurrency. February 19, 2014

Announcements. me your survey: See the Announcements page. Today. Reading. Take a break around 10:15am. Ack: Some figures are from Coulouris

RFC 003 Event Service October Computer Science Department October 2001 Request for Comments: 0003 Obsoletes: none.

An Introduction to Erlang

Fault Tolerance. Goals: transparent: mask (i.e., completely recover from) all failures, or predictable: exhibit a well defined failure behavior

Erlang. Joe Armstrong.

Reactive Application Development

Chapter 4: Threads. Operating System Concepts 9 th Edition

Principles of Software Construction: Objects, Design, and Concurrency. Concurrency: More Design Tradeoffs School of Computer Science

OPERATING SYSTEM. Chapter 4: Threads

CloudI Integration Framework. Chicago Erlang User Group May 27, 2015

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions

Alfresco repo under concurrent write load. Alexey Vasyukov, ITD Systems

Introduction to Erlang. Franck Petit / Sebastien Tixeuil

IGL S AND MOUNT NS. Taking AKKA to Production

Introduction to Asynchronous Programming Fall 2014

SE350: Operating Systems

Chapter 4: Threads. Operating System Concepts 9 th Edition

Reminder from last time

Chapter 4: Threads. Operating System Concepts 9 th Edit9on

Chapter 4: Processes

Chapter 5 Distributed Objects and Remote Invocation

Jade: Java Agent DEvelopment Framework Overview

Chapter 4: Threads. Chapter 4: Threads

Actors in the Small. Making Actors more Useful. Bill La

Exercise Unit 2: Modeling Paradigms - RT-UML. UML: The Unified Modeling Language. Statecharts. RT-UML in AnyLogic

Distributed Programming

An actor system for Scala.js Semester project, Fall 2013

02 - Distributed Systems

02 - Distributed Systems

Fault Tolerance Causes of failure: process failure machine failure network failure Goals: transparent: mask (i.e., completely recover from) all

Building Reactive Applications with Akka

Chapter 4: Threads. Chapter 4: Threads

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

Appendix A - Glossary(of OO software term s)

ebus Programmer s Manual

Erlang: An Overview. Part 2 Concurrency and Distribution. Thanks to Richard Carlsson for most of the slides in this part

Transcription:

CMPT 435/835 Tutorial 1 Actors Model & Akka Ahmed Abdel Moamen PhD Candidate Agents Lab ama883@mail.usask.ca 1

Content Actors Model Akka (for Java) 2

Actors Model (1/7) Definition A general model of concurrent computation for developing parallel, distributed, and mobile systems. 3

Actors Model (2/7) Structured programming considers all programs as composed of three control structures. Objects encapsulate data (state) and behavior, separating the interface of an object (what an object does) from its representation (how it does it). Actors extend the advantages of objects to concurrent computation by separating control (where and when) from the logic of a computation. 4

Actors Model (3/7) An Actor encapsulates a thread of execution with a collection of objects. Only the actor s thread may access its objects directly and change their state. Actors communicate by sending messages to each other. Messages are sent asynchronously. Messages are not necessarily processed in the order they are sent or received. collection of objects Thread mailbox

Actors Model (4/7) Each actor is a computational entity, that encapsulates a thread and a state, can concurrently: send a finite number of messages to other actors; create a finite number of new actors; designate a new behavior to process subsequent messages (become). 6

Actors Model (5/7) The key semantic properties of the pure (standard) Actors model: Encapsulation of state ; Atomic execution of a method in response to a message; Fairness in scheduling actors and in the delivery of messages; Location transparency enabling distributed execution and mobility. 7

Actors Model (6/7) Message passing Recipients of messages are identified by addresses (actor names); Addresses cannot be guessed, which means an actor can only communicate with actors whose addresses it has; Direct and asynchronous communication; No requirement on order of message arrival; Fairness in the delivery of messages. 8

Actors Model (7/7) Actors model has been applied in both research and industrial fields. Actor languages: ErLang, Scala, SALSA, ABCL, etc. Actor libraries: ActorFoundry (Java), Akka (Java & Scala), Pulsar (Python), CAF (C++), etc. In practice, Actors model is usually extended for ease of use. 9

Content Actors Model Akka (for Java) 10

Akka General Information (1/18) Akka is a toolkit and runtime for building highly concurrent, distributed, and fault tolerant eventdriven applications on the JVM. About the name A palindrome of letters A and K as in Actor Kernel; The name of a Swedish mountain (where does the logo come from). The current version of Akka supports both Java and Scala. Scala started to use Akka as its default actor library from version 2.10.0. 11

Akka - Resources (2/18) Official website: http://akka.io/ A simple step-by-step tutorial (Java): http://doc.akka.io/docs/akka/2.0.2/intro/getti ng-started-first-java.html The reference manual for the latest stable release v2.3.13: http://doc.akka.io/docs/akka/2.3.13/akkajava.pdf?_ga=1.187277096.1279128105.1440188 263 12

Akka Creating Actors (3/18) Step 1/3 (Defining) Actors in Java are implemented by extending the UntypedActor class and implementing the onreceive method. import akka.actor.untypedactor; public class MyActor extends UntypedActor { public void onreceive(object message) throws Exception { if (message instanceof String) { System.out.println(message); } else { unhandled(message); }}} 13

Akka Creating Actors (cont.) (4/18) Step 2/3 (Configuring) Props is a configuration class to specify options for the creation of actors. import akka.actor.props; Props props1 = Props.create(MyActorA.class); Props props2 = Props.create(MyActorB.class, arg1, arg2); 14

Akka Creating Actors (cont.) (5/18) Step 3/3 (Creating) Actors are created by passing a Props instance into the actorof factory method which is available on ActorSystem and ActorContex. Use ActorSystem to create top-level actors which are supervised by the actor system s provided guardian actor. Use actor s context (ActorContex) to create a child actor. import akka.actor.actorref; Import akka.actor.actorsystem; final ActorSystem system = ActorSystem.create( MySystem ); final ActorRef mytoplevelactor = system.actorof(props.create(myactora.class), myactor1 ); class A extends UntypedActor { final ActorRef mychildactor = getcontext().actorof(props.create(myactorb.class, myactor2 ); } 15

Akka Creating Actors (cont.) (6/18) UntypedActor APIs getself(), references to the ActorRef of the actor. getsender(), references to the sender actor of the last received message. getcontext(), exposes contextual information for the actor and the current message. User-overridable life-cycle hooks prestart(), executed after starting the actor (and also by postrestart() as default); prerestart() postrestart() poststop(), executed after stopping the actor. 16

AkkaAkka Messages (cont.) (7/18) Send messages tell() sends a message asynchronously and returns immediately. ask() sends a message asynchronously and returns a Future representing a possible reply. tell() is preferred due to performance concern. For both methods, actors have the option of passing along their own references (ActorRef). 17

Akka Messages (cont.) (8/18) tell() (fire-and-forget) No blocking waiting for a message. Giving the best concurrency and scalability characteristics. The sender reference can be retrieved by the receiving actor via its getsender() method while processing the message. // The second argument to tell() can be null. target.tell(message, getself()); 18

Akka Messages (cont.) (9/18) ask() (send-and-receive-future) Involving actors as well as futures. The receiving actor must reply with getsender().tell(reply, getself()) in order to complete the returned Future with a value, or send a Failure message to the sender to complete the Future with an exception. If the actor does not complete the future, it will expire after the timeout period, specified as parameter to the ask() method. 19

Akka Messages (cont.) (10/18) import static akka.pattern.patterns.ask; import scala.concurrent.future; import scala.concurrent.duration.duration; import akka.dispatch.futures; import akka.util.timeout; // Sender Timeout timeout = new Timeout(Duration.create(5, "seconds")); Future<Object> future = ask(actor, msg, timeout); String result = (String) Await.result(future, timeout.duration()); // Receiver try { String result = operation(); getsender().tell(result, getself()); } catch (Exception e) { getsender().tell(new akka.actor.status.failure(e), getself()); throw e; } 20

Akka Messages (cont.) (11/18) Forward messages A message can be forward from one actor to another. The original sender reference is maintained. The context of the mediator actor should be passed along as well. This can be useful when writing actors that work as routers, load-balancers, etc. target.forward(result, getcontext()); 21

Akka Messages (cont.) (12/18) Receive messages When an actor receives a message, it is passed into the onreceive() method, which is an abstract method on the UntypedActor base class that needs to be defined. The UntypedActorContext setreceivetimeout() defines the inactivity timeout after which the sending of a ReceiveTimeout message is triggered. 22

Akka Messages (cont.) (13/18) import akka.actor.actorref; import akka.actor.receivetimeout; import akka.actor.untypedactor; import scala.concurrent.duration.duration; public class MyReceiveTimeoutUntypedActor extends UntypedActor { public MyReceiveTimeoutUntypedActor() { getcontext().setreceivetimeout(duration.create("30 seconds")); } public void onreceive(object message) { if (message.equals("hello")) { } else if (message instanceof ReceiveTimeout) { } else { unhandled(message); }}} 23

Akka Messages (cont.) (14/18) Reply to messages getsender() can be used to get a handle of the sender for replying to a message. The handle returned by getsender() can also be stored for later using. If the sender is not provided, the reply is sent to a dead-letter actor. public void onreceive(object message) { Object result = caculateresult(). getsender().tell(result, getself()); } 24

Akka Hotswapping (15/18) The getcontext().become() method can be called with an actor to hotswap the actor s message loop. import akka.japi.procedure; public class HotSwapActor extends UntypedActor { Procedure<Object> angry = new Procedure<Object>() { public void apply(object message) { if (message.equals("bar")) { getsender().tell("i am already angry?", getself()); } else if (message.equals("foo")) { getcontext().become(happy); }}}; } public void onreceive(object message) { if (message.equals("bar")) { getcontext().become(angry); } else if (message.equals("foo")) { getcontext().become(happy); } else { unhandled(message); }} Procedure<Object> happy = new Procedure<Object>() { public void apply(object message) { if (message.equals("bar")) { getsender().tell("i am already happy :-)", getself()); } else if (message.equals("foo")) { getcontext().become(angry); }}}; 25

Akka Stopping Actors (16/18) Actors are stopped by invoking the stop method of a ActorRefFactory. ActorContext, stopping child actors; ActorSystem, stopping top-level actors. Termination of an actor: suspends its mailbox processing; sends a stop command to all its children; keeps processing the internal termination notifications from its children until the last one is gone; terminating itself. Upon ActorSystem.shutdown(), the whole system will be terminated in the fore-mentioned manner. 26

Akka - Logging (17/18) LoggingAdapter has different methods for handling error, warning, info, and debug information, respectively. The logging options can be configured in the application configuration file (%AKKA_HOME%\config\application.conf). import akka.event.logging; import akka.event.loggingadapter; class MyActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void prestart() { log.debug("starting"); } public void prerestart(throwable reason, Option<Object> message) { log.error(reason, "Restarting due to [{}] when processing [{}]", reason.getmessage(), message.isdefined()? message.get() : ""); } } 27

Akka Sample Programs (18/18) HelloWorld. Pi (The first tutorial of Akka). How to run Akka programs from commandline. 28

THANKS! Q & A 29