all about scala
DESCRIPTION
ILTechTalk presentationTRANSCRIPT
1 Created on 10/01/2012 of 99
Yardena MeymannJanuary 10, 2012http://www.meetup.com/ILTechTalks/
ALL* ABOUT SCALA *ALL I COULD FIT IN 90 MINUTES PRESENTATION,
IN FACT THERE IS MUCH MORE TO SCALA…
2 Created on 10/01/2012 of 99
NAVIGATION
– Background
– Scala basics
– OOP in Scala
– FP in Scala
– Concurrency
– Tools
– Resources
3 Created on 10/01/2012 of 99
IT DOES NOT HAVE TO BE JAVA
it is tastier when you mix them!
Java
Java Compiler
Bytecode
Java Virtual MachineCA FE
BA BE
Scala
Scala Compiler
Bytecode
Groovy
Groovy Compiler
Bytecode
4 Created on 10/01/2012 of 99
WHAT IS SCALA
– Object oriented and functional
– Statically typed - advanced type system
– Compiled to JVM bytecode but also to CLR, and to JavaScript (in progress);
works with Dalvik
– High performance
– Very good interoperability with Java
– Support for modularity and extensibilityDSL friendly
5 Created on 10/01/2012 of 99
JAVA AND SCALA TIMELINE
lawsuit 2001
2.9 2011 2.3 2007
2.7 2008 2.8 2010
2009
€2.3 million 2011 2011
Java 7 (Dolphin)
2011
6 Created on 10/01/2012 of 99
THEN AND NOW
“If I were to pick a language to use today other than Java, it would be Scala”
James Gosling
7 Created on 10/01/2012 of 99
TOOLS
– IDE: • built-in REPL, Scala IDE (based on Eclipse), IntelliJ and NetBeans plug-ins, ENSIME
– Tools• https://wiki.scala-lang.org/display/SW/Tools+and+Libraries
• integration modules for almost every popular Java framework
scala>
8 Created on 10/01/2012 of 99
OPEN SOURCE
9 Created on 10/01/2012 of 99
INDUSTRY
10 Created on 10/01/2012 of 99
BOOKS
11 Created on 10/01/2012 of 99
JOBS
12 Created on 10/01/2012 of 99
TYPESAFE
13 Created on 10/01/2012 of 99
HELLO SCALA!
Let’s see some code now…
14 Created on 10/01/2012 of 99
HELLO SCALA
15 Created on 10/01/2012 of 99
SCALA REPL
16 Created on 10/01/2012 of 99
HELLO SCALA
package com.hp.scala
object HelloScala {
def main(args: Array[String]) {
println(“Hello Scala”)
}
}
package com.hp.scala;
public class object HelloScala {
public static void def main(String[] args: Array[String]) {
System.out.println(“Hello Scala”);
}
}
17 Created on 10/01/2012 of 99
HELLO SCALA - VARIABLES
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
}
}
18 Created on 10/01/2012 of 99
HELLO SCALA – TYPE INFERENCE
object HelloScala { def main(args: Array[String]) {
val msg = “Hello Scala”println(msg)
}}
19 Created on 10/01/2012 of 99
VAL VS. VAR
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
msg = “Goodbye Java”
println(msg)
}
}
20 Created on 10/01/2012 of 99
VAL VS. VAR
object HelloScala {
def main(args: Array[String]) {
var msg = “Hello Scala”
println(msg)
msg = “Goodbye Java”
println(msg)
}
}
21 Created on 10/01/2012 of 99
METHODS (VERBOSE)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String): String = {
return “Hello ” + who
}
}
22 Created on 10/01/2012 of 99
METHODS (SHORTER)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String): String = {
“Hello ” + who
}
}
23 Created on 10/01/2012 of 99
METHODS (SHORTER YET)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String) = {
“Hello ” + who
}
}
24 Created on 10/01/2012 of 99
METHODS (SHORT)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String) = “Hello ” + who
}
25 Created on 10/01/2012 of 99
ARRAY ACCESS
object HelloScala {
def main(args: Array[String]) {
println(hello(args(0))
//args(0) is a shortcut for args.apply(0)
}
def hello(who: String) = “Hello ” + who
}
26 Created on 10/01/2012 of 99
CONDITION
object HelloScala {
def main(args: Array[String]) {
if (!args.isEmpty) println(hello(args(0))
}
def hello(who: String) = “Hello ” + who
}
//isEmpty() method has no arguments, and therefore can be invoked without the ()
27 Created on 10/01/2012 of 99
IF EXPRESSION, NOT STATEMENT
object HelloScala {
def main(args: Array[String]) {
println(hello(
if (args.isEmpty) “Anonymous” else args(0)))
}
def hello(who: String) = “Hello ” + who
}
28 Created on 10/01/2012 of 99
FUNCTION OBJECT
object HelloScala {
def main(args: Array[String]) { …
}
val hello = (who: String) => “Hello “ + who
// equivalent to
//val hello = new Function1[String, String] {
// def apply(who: String): String = “Hello “ + who
//}
}
29 Created on 10/01/2012 of 99
FOREACH
object HelloScala {
def main(args: Array[String]) {
args.foreach(arg => println(hello(arg)))
}
def hello…
}
//example of anonymous function object
30 Created on 10/01/2012 of 99
OPERATORS, INFIX SYNTAX
def hello(who: String) = “Hello ”.+(who)
//same as “Hello ” + who
//NOTE that this is an example, not a recommended coding style:
def main(args: Array[String]) {
Console println hello (if (args isEmpty) “Anonymous” else args apply 0)
}
31 Created on 10/01/2012 of 99
MATCH EXPRESSIONS
– Matching on values (Java’s switch)
val times = 1times match { case 1 => "one" case 2 => "two" case _ => "some other number" }
– No fall-through!
– Matching with guards
n match { case it if 0 until 5 contains it => "less than five" case it if 5 until 10 contains it => "less than ten" case _ => "a lot“}
32 Created on 10/01/2012 of 99
EXCEPTIONS
– Throwing an exception looks the same as in Java
– You catch exceptions using the syntax:
– NOTE: All exceptions in Scala are runtime
33 Created on 10/01/2012 of 99
CREATING A SEQUENCE
–Array(1,2,3)•Arrays are mutable
–List(3.14, 2.72, 1.62)•Lists are by default immutable, singly-linked•Nil is an empty list
–Map: val romanNumeral =
Map(1 ->"I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V“ )
// x -> y creates a tuple (x,y)
34 Created on 10/01/2012 of 99
MAP VALUES – ANOTHER OPTION
–What if key is not in the Map?
–Map.get returns an Option: •Some(value), value can be retrieved with get •or None
–getOrElse method allows to specify default:•treasureMap.getOrElse(1, “Oops”)•treasureMap.getOrElse(4, “Oops”)
–Safe alternative to null-checks
Scala Programming
35 Created on 10/01/2012 of 99
OPERATING WITH A SEQUENCE
– foreach(E=>Unit),
– filter(E=>Boolean),
– map(E=>X),
– reduceLeft((E,E)=>E),
– take(Int),
– drop(Int),
– indexOf(E),
– exists(E=>Boolean),
– remove(E=>Boolean),
– reverse,
– sort((E,E)=>Boolean),
– head,
– tail,
– … more later
36 Created on 10/01/2012 of 99
RICH WRAPPERS
– A Range can be created: ‘a’ to ‘z’ or 1 until 10
– Scala compiler made an implicit conversion of Int to scala.runtime.RichInt• To check if conversion is available: implicitly[Int => RichInt]
(in REPL first import scala.runtime._)• Alternatively: scalac –Xprint:typer
– Another Example: • reg-exp• "()?(\\d+)(\\.\\d*)?".r
37 Created on 10/01/2012 of 99
PLACEHOLDER
(1 to 10) filter ((i: Int) => i%2 == 0) mkString “,”
or equivalent shorter version:
… filter (i => i%2 == 0)
or yet shorter using placeholder:
… filter (_ %2 == 0)
(1 to 10).reduceLeft((acc: Int, i: Int) => acc + i)
or equivalent shorter version:
… reduceLeft((acc, i) => acc + i)
or yet shorter using placeholders:
… reduceLeft(_ + _)
38 Created on 10/01/2012 of 99
CLOSURES
–So far, function literals have referred only to passed parameters(x: Int) => x > 0
–You can, however, refer to variables defined elsewhere(x: Int) => x + more // how much more?
–more is a free variable, because the function literal does not itself give a meaning to it.
–x variable, by contrast, is a bound variable.
39 Created on 10/01/2012 of 99
CLOSURES
The function value (the object) that’s created at runtime from addMore function literal is called a closure.
The name arises from the act of “closing” the function literal by “capturing” the bindings of its free variables
40 Created on 10/01/2012 of 99
EXAMPLEdef tryWithLogging (s: => Unit) {
try {
s
} catch {
case ex: Exception => ex.printStackTrace()
}
}
val file = new File(“test.txt”)
tryWithLogging {
val writer = new PrintWriter(file)
writer.println(“this is a test”)
}
If you’re passing exactly one argument to a method, you can use curly braces instead of parentheses to surround it.
41 Created on 10/01/2012 of 99
HELLO SCALA – FOR COMPREHENSION
object HelloScala {
def main(args: Array[String]) {
for (arg ← args) println(hello(arg)))
}
def hello…
}
42 Created on 10/01/2012 of 99
MORE ON FOR EXPRESSION
–map alternative – yield:def scalaFiles =
for {
file (new java.io.File(".")).listFiles
if file.getName.endsWith(".scala")
} yield file
•When the for expression completes, the result will include all of the yielded values contained in a single collection.
•The type of the resulting collection is based on the kind of collections processed in the iteration clauses.
43 Created on 10/01/2012 of 99
SCALA HIERARCHY
– Nothing is the subtype of all other types. • It has no instances. • It is used primarily for defining other types in a
type-safe way, such as the special List subtype Nil.
– Null has one instance, null, corresponding to the runtime’s concept of null.
– FunctionN[-T1, -T2, …, -TN, +R] a
function that takes N arguments
– Product - arity and getting nth item in a “cartesian product”. • Subtraits are defined for Product,
called ProductN, for dimension N from 1 through 22.
– TupleN case classes for arity N = 1 through 22. • Tuples support the literal syntax (x1, x2, …, xN)
44 Created on 10/01/2012 of 99
CLASSES
OOP in Scala
45 Created on 10/01/2012 of 99
SIMPLE CLASS
–Like in Java classes are defined with class and instances created with new
–Declaring properties is much simpler
Java
public class Person { private String name = null; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
Scala
class Person (var name: String)
…person = new Person(“Martin”)println(person.name)
46 Created on 10/01/2012 of 99
SIMPLE CLASS
scala> class Lang {
| val name: String = “Scala"
| def add(m: Int, n: Int): Int = m + n
| }
defined class Lang
scala> val lang = new Lang
lang: Lang = Lang@e74a51
scala> lang.add(1, 2)
res1: Int = 3
scala> lang.name
res2: String = “Scala"
47 Created on 10/01/2012 of 99
CLASS SYNTAX
48 Created on 10/01/2012 of 99
EXTENDING CLASSES
class ArrayElement(conts: Array[String]) extends Element {
def contents: Array[String] = conts
}
class LineElement(s: String) extends ArrayElement(Array(s)) {
override def width = s.length
override def height = 1
}
49 Created on 10/01/2012 of 99
SINGLETON & COMPANION OBJECTS
– Scala is more object-oriented than Java is that classes in Scala cannot have static members. Instead, Scala has singleton objects.
– A singleton object definition looks like a class definition, except instead of the keyword class you use the keyword object.
– When a singleton object shares the same name with a class, it is called that class’s companion object. object Rational {
…
}
– A singleton object that does not share the same name with a companion class is called a standalone object.
50 Created on 10/01/2012 of 99
COMPANION OBJECT AS A FACTORY
– Companion objects are excellent fit for implementing Factory design patterns
– Naming the method apply allows invocation like Array(“a”, “b”, “c”) instead of Array.apply(“a”, “b”, “c”)
51 Created on 10/01/2012 of 99
BUILDER PATTERN IN SCALA
– From Josh Bloch’s “Effective Java” 2nd ed.: public class NutritionFacts { private final int servingSize; // (mL) required private final int servings; // (per container) required private final int calories; // optional private final int fat; // (g) optional private final int sodium; // (mg) optional private final int carbohydrate;// (g) optional … }
– In Scala:class NutritionFacts(servingSize, servings, calories = 0, fat = 0, sodium = 0, carbohydrate = 0)
Creating an instance:
new NutritionFacts(servings = 3, servingSize = 200, fat = 1)
52 Created on 10/01/2012 of 99
CASE CLASSES – VALUE OBJECTScase class Point(x: Double, y: Double)
abstract class Shape() { def draw(): Unit }
case class Circle(center: Point, radius: Double) extends Shape() {
def draw() { … }
}
case class Rectangle(x: Point, height: Double, width: Double) extends Shape() {
def draw() { … }
}
case class Triangle(point1: Point, point2: Point, point3: Point) extends Shape() {
def draw() { … }
}
– Using the case modifier makes the Scala compiler add some syntactic conveniences to your class•…
53 Created on 10/01/2012 of 99
CASE CLASS MAGIC
– Compiler automatically creates factory method: val c = Circle(Point(2.0,1.0),3.0) instead of
val c = new Circle(new Point(2.0,1.0),3.0)
– All constructor arguments automatically become immutable fields
– Compiler automatically implements equals, hashCode, and toString methods to the class, using the fields specified as constructor argumentscase classes are always compared structurally
– Compiler adds a copy method for making modified copiesThe method works by using named and default parameters. You specify the changes you’d like to make by using named parameters. For any parameter you don’t specify, the value from the old object is used.
val r = Rectangle(Point(1.0,2.0), 3.0, 4.0)
r.copy(height=5.0)
– We can pattern match on case classes…
54 Created on 10/01/2012 of 99
CASE CLASSES – PATTERN MATCHING
def matchOn(shape: Shape) = shape match {
case Circle(center, radius) => println("Circle: center = "+center+", radius = "+radius)
case Rectangle(x, h, w) => println("Rectangle: lower-left = "+x+", height = "+h+", width = "+w)
case Triangle(p1, p2, p3) => println("Triangle: point1 = "+p1+", point2 = "+p2+", point3 = "+p3)
case _ => println("Unknown shape!"+shape)
}
val shapesList = List(
Circle(Point(0.0, 0.0), 1.0), Circle(Point(5.0, 2.0), 3.0), Rectangle(Point(0.0, 0.0), 2, 5), Rectangle(Point(-2.0, -1.0), 4, 3), Triangle(Point(0.0, 0.0), Point(1.0, 0.0), Point(0.0, 1.0))
)
shapesList.foreach { shape => matchOn(shape) }
55 Created on 10/01/2012 of 99
MIXIN COMPOSITION WITH TRAITS
56 Created on 10/01/2012 of 99
TRAITS
– A trait definition looks just like a class definition except that it uses the keyword traittrait Philosophical { def philosophize() { println("I consume memory, therefore I am!") }}
– Once a trait is defined, it can be mixed in to a class using either the extends or with keywordsclass Frog extends Philosophical { … }
– Traits facilitate multiple inheritance: a class can mix in any number of traits. “He who defs last defs best”.class Animal { … } trait HasLegs { val legsNumber : Int }class Frog extends Animal with Philosophical with HasLegs { override val legsNumber = 4override def philosophize() { println(“It ain't easy being green”) }}
57 Created on 10/01/2012 of 99
THE TRAITS OF TRAITS
– Traits can be also mixed in when creating individual objects:val frog = new Animal with Philosophical
– You can do anything in a trait definition that you can do in a class definition, with only two exceptions:• trait cannot have any “class” parameters, i.e., parameters passed to the primary constructor of a classtrait NoPoint(x: Int, y: Int) // Does not compile
• in classes, super calls are statically bound, in traits, they are dynamically bound (enables stackable modifications pattern)
– Trait, like any class can have a companion object• selfless trait – trait Util { … }; object Util extends Util
58 Created on 10/01/2012 of 99
TRAITS – A PRACTICAL EXAMPLE
class Trade(refNo: String, account: String, instrument: String, quantity: Int, unitPrice: Int) { // principal value of the trade def principal = quantity * unitPrice}
trait Tax { def calculateTax }
trait Commission { def calculateCommission}
val trade = new Trade(..) with Tax with Commission { // implementations def calculateTax = principal * 0.2 def calculateCommission = principal * 0.15}
59 Created on 10/01/2012 of 99
TRAITS – REQUIRE (SELF TYPE)
– Sometimes you want to constrain what the trait can be mixed in with, for example:// abstractions Tax and Commission should be constrained to be used with the Trade abstraction only
trait Tax { self: Trade => def calculateTax = principal*0.2 //refers to principal of trade }
trait Commission { self: Trade => def calculateCommission = principal*0.15 //refers to principal of trade}
– When you say B extends A, then B is an A, while here you define the relationship of B requires an A
60 Created on 10/01/2012 of 99
TRAITS – DI WITH THE CAKE PATTERN
– The pattern based on Scala traits was first introduced by Martin Odersky’s paper “Scalable Component Abstractions”
– The pattern also uses nested classes: Scala, like Java, supports nesting of classes in one another
– Demo
http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html
61 Created on 10/01/2012 of 99
ANNOTATIONS – JPA EXAMPLE@Entity @NamedQuery{val name = "findAllBook", val query = "SELECT b FROM Book b"}
class Book extends Id with Description { @Column{val nullable = false} @BeanProperty var title: String @BeanProperty var price: Float @BeanProperty var isbn: String @BeanProperty var nbOfPage: Int @BeanProperty var illustrations: Boolean }trait Id { @javax.persistence.Id @GeneratedValue{val strategy = GenerationType.IDENTITY} @BeanProperty var id: Long}trait Description { @Column{val length = 2000} @BeanProperty var description: String }
62 Created on 10/01/2012 of 99
PACKAGES
– You can place code into named packages in Scala:• Either place the contents of an entire file into a package by putting a package clause at the top of the file (like in Java)
• Or follow a package clause by a section in curly braces that contains the definitions that go into the package (like C# namespaces).
– Objects are a useful tool for organizing static functions.
63 Created on 10/01/2012 of 99
PACKAGE OBJECTS
– Scala version 2.8 introduces a new scoping construct called package objects• they are used to define types, variables, and methods that are visible at the level of the corresponding package
• they can contain aliases to classes and objects• they provide a clear separation between the abstractions exposed by a package and the implementations that should be hidden inside it
package object scala { type Iterable[+A] = scala.collection.Iterable[A] val Iterable = scala.collection.Iterable…
}
64 Created on 10/01/2012 of 99
IMPORT
– Use import in REPL and anywhere in your .scala file • Single file: import package.Class • All files: import package._• Multiple files: import package.{A,B,C}• Renaming: import package.{A=>B}• Import all except: import package.{A=>_, _}
– Example: import java.sql.{Date=>SDate,_}
– Imports are relative, but you can use _root_. … to import a FQN
– Import also works with Objects
– You can limit the scope of any declaration, including import, with locally { … }
65 Created on 10/01/2012 of 99
FUNCTIONAL PROGRAMMINGBASICS
Unleash the power of Lambda
66 Created on 10/01/2012 of 99
OVERVIEW
– In mathematics, functions have no side effects• No matter how much work sin(x) does, all the results are returned and assigned to y. No global state of any kind is modified internally by sin(x). Hence, we say that such a function is free of side-effects or pure.
– This obliviousness to the surrounding context is known as referential transparency. • You can call such a function anywhere and be confident that it will always behave the same way. If no global state is modified, concurrent invocation of the function is straightforward and reliable.
67 Created on 10/01/2012 of 99
OVERVIEW
– In functional programming variables are immutable.• In the expression y = sin(x), once you pick x, then y is fixed
• Functional programming languages prevent you from assigning a new value to a variable that already has a value.
• Besides concurrency, immutability has other benefits…
– “Functional manifesto”• val over var
• Composition over inheritance
• Immutable collections
• Recursion over imperative iteration
• Pattern matching over encapsulation
• …
68 Created on 10/01/2012 of 99
LAZY VAL
– If you prefix a val definition with a lazy modifier, the initializing expression on the right-hand side will only be evaluated the first time the val is used.
– unlike def, lazy val is never evaluated more than once.• after the first evaluation of a lazy val the result of the evaluation is stored, to be reused when the same val is used subsequently.
69 Created on 10/01/2012 of 99
CALL BY NAME PARAMETERS
–Typically, parameters to functions are by-value parameters – the value of the parameter is determined before it is passed to the function
–Sometimes we don’t want a parameter evaluated until it’s accessed within our function
–A by-name parameter is specified by omitting the parentheses that normally accompany a function parameterdef myCall (parameter: => ReturnType)
70 Created on 10/01/2012 of 99
CALL BY NAME PARAMETERS USE-CASE– When logging, we create messages by concatenating Strings, even
if we don't use these messages in the end because the logging level is not enabled.
– To fix the problem, we often insert manual checks in client code whether the logging level is enabled, e.g. by calling if (logger.isDebugEnabled()) logger.debug(…)
– SLF4S, Scala logging library, uses by-name parametersdef debug(msg: => String) { require(msg != null, "msg must not be null!") if (slf4jLogger.isDebugEnabled) slf4jLogger debug msg}
– SLF4S also provides Logging trait that can be mixed in into any classclass MyClazz extends SomeClazz with Logging...logger debug "SLF4S just rocks!"...
71 Created on 10/01/2012 of 99
CURRYING
– Currying – a way to write functions with multiple parameter lists. • For instance def f(x: Int)(y: Int) is a curried function with two parameter lists.
• A curried function is applied by passing several arguments lists, as in: f(3)(4).
– Examples:def plainOldSum(x: Int, y: Int) = x + yplainOldSum(1, 2)
def curriedSum(x: Int)(y: Int) = x + ycurriedSum(1)(2)
val onePlus: (Int) => Int = curriedSum(1)_
onePlus(2) //3
72 Created on 10/01/2012 of 99
CURRYING EXAMPLE
– foldLeft/Right
– withResource (the loan pattern)def using[R <: Closeable] (resource: R)(block: R => Unit) { try { block(resource) } finally { if (resource != null) resource.close() }}
• Usage Example:
using(new BufferedReader(new FileReader("file"))) { r => … r.readLine …}
73 Created on 10/01/2012 of 99
PARTIALLY-APPLIED FUNCTIONS
– A partially applied function is an expression in which you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments.scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (a: Int,b: Int,c: Int)Int
scala> val a = sum _
a: (Int, Int, Int) => Int = <function3>
a(1, 2, 3) //6
supplying some arguments: val b = sum(1, _: Int, 3)
b: (Int) => Int = <function1>
scala> b(2) //6
74 Created on 10/01/2012 of 99
CONCURRENCY IN SCALA
Introducing Actors
75 Created on 10/01/2012 of 99
MOTIVATION
Moor’s Law• “The number of transistors on a chip will double approximately every 18 months”
Gordon E. Moore, 1965
Free LunchFree and regular performance gains, even without releasing new versions or doing anything special
76 Created on 10/01/2012 of 99
FREE LUNCH IS OVER
– Hardware crossed a boundary in the early 2000s: • chips got big enough, cycle speed got fast enough • a signal can no longer reach the whole chip in a clock cycle• problems with heat dissipation
– Processor manufacturers have turned towards multi-core processors Capable of doing multiple calculations in parallel • CPU speeds are likely to stay relatively flat in the near future • The speedup of a program using multiple processors in parallel computing is limited by the sequential fraction of the program.
77 Created on 10/01/2012 of 99
SHARED STATE CONCURRENCY
–Shared mutable state is problematic
–We need locking mechanism
–Thread concurrently executes code sections•Contains resources that must be shared•Synchronized in order to guarantee
−Correct ordering
−Visibility
−Data consistency
78 Created on 10/01/2012 of 99
PROBLEMS WITH LOCKING
–Hard to program correctly•Race conditions•Also hard to test and debug
–Synchronizing too much•Deadlocks•Makes your program serial
79 Created on 10/01/2012 of 99
ALTERNATIVES
–Message Passing Concurrency (Actors)
–Software Transactional Memory
–Dataflow Concurrency
80 Created on 10/01/2012 of 99
ACTORS
–Message-passing instead of shared state
–Originated: •Carl Hewitt (early 70s)•Gul Agha (80s)
–Popularized by Erlang implementation•A pure functional, dynamically typed language invented in 1986 at Ericsson
–Actors are related to original OO ideas •Actors encapsulate state and behavior (like objects)•Actors are logically active (unlike most objects)
81 Created on 10/01/2012 of 99
ACTORS
– No shared state between actors
– Asynchronous message-passing
– Mailbox to buffer incoming messages
– React to received messages by executing a behavior function•can only change the state of the actor itself
•can send messages to other actors
– Actors never share state and thus never need to compete for locks for access to shared data
82 Created on 10/01/2012 of 99
AKKA
– Akka is the platform for next generation event-driven, scalable, and fault-tolerant architectures on the JVM
– Written in Scala, can be used with Scala or Java
– Each actor instance runs in only one thread at a time, so no synchronization is required for actor state.
– Akka dispatcher schedules actors on threads – or even on multiple machines – as needed. Can have millions of actors, an actor does not “use up” a thread.
83 Created on 10/01/2012 of 99
SIMPLE AKKA ACTOR
case object Tick
class Counter extends Actor {
private var counter = 0
def receive = {
case Tick =>
counter += 1
println(counter)
}
}
val counter = actorOf[Counter]
counter.start
84 Created on 10/01/2012 of 99
SEND
–Fire and forgetcounter ! Tick
–Uses Future under the hood (with time-out)val result = (actor !! Message).as[String]
–Returns the Future directlyval future = actor !!! Message
future.await
val result = future.get
...
Futures.awaitOne(List(fut1, fut2, ...))
Futures.awaitAll(List(fut1, fut2, ...))
85 Created on 10/01/2012 of 99
REPLY
class SomeActor extends Actor {
def receive = {
case User(name) =>
// use reply
self.reply(“Hi ” + name)
}
}
store away the sender to use later or somewhere else
... = self.sender
86 Created on 10/01/2012 of 99
SCALA AND AKKA
– Immutable messages : case classes, tuples, lists
– Dispatchers
– Let it fail – Supervisor Hierarchies• One for One
• All for One
• Supervise the supervisor
– Remote actors
– Transactors: STM using Actors
87 Created on 10/01/2012 of 99
TOOLS
Build, testing, etc.
88 Created on 10/01/2012 of 99
SBT – SIMPLE BUILD TOOL
– Build your projects using Scala
– Create an sbt shell script: java -Xmx512M -jar sbt-launch.jar "$@“
– Launch it: sbt
– Interactive mode: e.g. compile
– Make an action run when a source file changes prefixing the action with ~.
– project/build/SbtDemoProject.scalaimport sbt._
class SbtDemoProject(info: ProjectInfo) extends DefaultProject(info) {
val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5" % "test"
lazy val hi = task { println("Hello World"); None }
override def compileOptions = super.compileOptions ++ Seq(Unchecked)
}
– In sbt console: reload
– In sbt console: hi
<dependency> <groupId>org.scala-tools.testing</groupId> <artifactId>specs_2.8.0</artifactId> <version>1.6.5</version> <scope>test</scope> </dependency>
89 Created on 10/01/2012 of 99
PLAY! FRAMEWORK
– Both Scala and Java friendly
– Stateless• Play is “share-nothing” so no need for communication between nodes
• State can be kept in your SQL or NoSQL store, in memcached, or browser cookies
– Emphasis on rapid development and good defaults, rather than absolute flexibility• No compile and restart; server compiles and recompiles on the fly, so just edit, reload, edit, reload. Compilation and other errors appear right in the browser.
– Try out the Java or Scala tutorials on the Play website
play new helloworld --with scala
play run
90 Created on 10/01/2012 of 99
UNIT TESTING
–To test in Scala you can use Java tools:• JUnit•TestNG
–Or frameworks built especially for Scala:•ScalaTest•Specs•ScalaCheck
Scala Programming
90
91 Created on 10/01/2012 of 99
UNIT TESTING
92 Created on 10/01/2012 of 99
UNIT TESTING – SCALATEST + JUNIT
– If you wish to use ScalaTest’s assertion syntax in your JUnit 3 test, however, you can instead subclass JUnit3Suite
– ScalaTest also has a JUnitWrapperSuite, which enables you to run existing JUnit tests written in Java with ScalaTest’s runner.
93 Created on 10/01/2012 of 99
TEST AS SPECIFICATION
94 Created on 10/01/2012 of 99
TEST AS SPECIFICATION
– In a FlatSpec, you write tests as specifier clauses. • You start by writing a name for the subject under test as a string,
• then should (or must or can),
• then a string that specifies a bit of behavior required of the subject,
• then in.
• In the curly braces following in, you write code that tests the specified behavior.
• In subsequent clauses you can write it to refer to the most recently given subject.
– When a FlatSpec is executed, it will run each specifier clause as a ScalaTest test. • FlatSpec (and ScalaTest’s other specification traits) generate output that reads more
like a specification when run.
Scala Programming
94
95 Created on 10/01/2012 of 99
TEST AS SPECIFICATION - SPECS
– specs is another open source testing framework inspired by Ruby’s RSpec
96 Created on 10/01/2012 of 99
PROPERTY-BASED TESTING
– ScalaCheck enables you to specify properties that the code under test must obey.
– For each property, ScalaCheck will generate test data and run tests that check whether the property holds.
97 Created on 10/01/2012 of 99
RESOURCES
Read more about Scala
98 Created on 10/01/2012 of 99
MORE ON SCALA
– http://www.scala-lang.org
– http://typesafe.com/
– Scala School http://twitter.github.com/scala_school/
– Programming In Scala http://www.artima.com/pins1ed/
– Programming Scala http://ofps.oreilly.com/titles/9780596155957/
– Scala Style Guide http://davetron5000.github.com/scala-style/
– StackOverflow http://stackoverflow.com/questions/tagged/scala
99 Created on 10/01/2012 of 99
THANK YOUIf you are interested in programming languages,
join http://www.lambda.org.il