SlideShare a Scribd company logo
1 of 32
Download to read offline
>
                                                             <----
                                                           --------->
                                                             <----
                                                               >




                      DEVELOPING THE SCALA BINDINGS FOR
                                    THE FLY OBJECT SPACE

                      Channing Walton	

                                       Nigel Warren
                      channing.walton@casualmiracles.com                nige@zink-digital.com




                                                                         http://www.casualmiracles.com/




CM, Java experience, CRE, UCL
Presentation about my experience porting from Java to Scala
INTRODUCTION


State safe co-ordination and communication between
         distributed system components.




                                     http://www.casualmiracles.com/
SPACES
Tuple Spaces - Linda (a coordination language)

         in - put a tuple into a space

         rd – get a copy of a tuple from the space

         out – remove tuple from the space



Subsequently …

         Java Spaces - Jini – Java

         Rinda – Ruby

         PyLinda – Python
         etc., etc.



                                                     http://www.casualmiracles.com/
FLY
Fly is an ‘Object Space’


    Network wide - Object level - Storage and Matching

    Matching – by Object Templates

    Object Serialisation – Native to a language or language neutural

    Leasing – Information and resources have prescribed lifetimes




                                                         http://www.casualmiracles.com/
FLY PRIME INTERFACE
public interface FlyPrime {

	
   long 	
 write(Object entry, long leaseTime);

	
   Object 	
   read(Object template, long waitTime);

	
   Object 	
   take(Object template, long waitTime);

}




                                                         http://www.casualmiracles.com/
DESIGN DIAMOND
    Minimise Interface




       Complexity




      Minimise Uses


                         http://www.casualmiracles.com/
FLY SPACE DESIGN
Minimal But Complete Interface     Write
                                   Read
                                   Take

         Threading
       Object Locking
        Distribution
         Matching
          Expiring


                                  Pthreads
       Minimal Use of              Sockets
       OS interfaces             Malloc - Free



                                           http://www.casualmiracles.com/
FLY SPACE INTERFACE HIERARCHY
                  Fly



    MultiFly                NotiFly
   writeMany              notifyWrite
   readMany                notifyTake
   takeMany


               FlyPrime
                 write
                 read
                  take


                             http://www.casualmiracles.com/
FLY SCALA

  Scala Application                    Scala Application
        Client                               Client

                                         Scala Space
Scala Space Interface
                                          Interface

    Scala Binding                        Scala Binding




                          Fly Server



                                           http://www.casualmiracles.com/
FROM JAVA TO SCALA

• Syntactic   Conversion

• Idiomatic API

• Idioms   Internally

• Actors

• Java   and Scala Compared

• What    Next?
                              http://www.casualmiracles.com/
SYNTACTIC
public interface NotiFly extends FlyPrime {
  boolean notifyWrite(Object template, NotifyHandler handler, long leaseTime);
  boolean notifyTake(Object template, NotifyHandler handler, long leaseTime);
}



trait NotiFly extends FlyPrime {
  def notifyWrite(template: AnyRef, handler: NotifyHandler, leaseTime: Long): Boolean
  def notifyTake(template:AnyRef, handler:NotifyHandler, leaseTime:Long):Boolean
}




                                                                http://www.casualmiracles.com/
SYNTACTIC
public static void main(String[] args) throws Exception {         def main(args: Array[String]) {

    FileInputStream f = new FileInputStream(new File(args[0]));        val f = new FileInputStream(new File(args(0)));
    DataInputStream dis = new DataInputStream(f);                      val dis = new DataInputStream(f);

    StatsDecoder decoder = new StatsDecoder();                         val decoder = new StatsDecoder();

    long time = dis.readLong();                                        var time = dis.readLong();
    while ( true ) {                                                   while (true) {
      int size = dis.readInt();                                          val size = dis.readInt();
      StatsBean [] beans = decoder.getStatsArray(dis);                   val beans = decoder.getStats(dis);
      Stats.writeStats(beans);                                           StatsPrinter.writeStats(beans);
      System.out.println("--------------");                              System.out.println("--------------");
      long nextTime = dis.readLong();                                    val nextTime = dis.readLong();
      Thread.sleep(nextTime-time);                                       Thread.sleep(nextTime - time);
      time = nextTime;                                                   time = nextTime;
    }                                                                  }
}                                                                  }



                                                                                             http://www.casualmiracles.com/
IDIOMS - OPTION

                      An Option represents an optional value

                      Two subclasses: Some and None

                      Java has … null




                                                               http://www.casualmiracles.com/




Experiment with Options in Java later
IDIOMS - OPTION

                      trait FlyPrime {
                          def read[T <: AnyRef](template: T, waitTime: Long):   Option[T]
                      }


                      fly.read(template, 0L) match {
                         case None => {
                            println("No ball in play")
                            serveBall(fly)
                            println("Served Ball - Please start a Pong")
                         }
                         case Some(gameBall) => {
                            println("Received ball - game on!")
                            returnBall(fly, gameBall)
                         }
                      }

                                                                                            http://www.casualmiracles.com/




pattern matching - scala can extract values from the matching pattern -
Some(ball)
no types
IDIOMS - OPTION

                     trait FlyPrime {
                         def read[T <: AnyRef](template: T, waitTime: Long):   Option[T]
                     }



                     fly.read(template, 0L) match {
                        case None => // do nothing
                        case Some(gameBall) => doSomething(gameBall)
                     }



                     fly.read(template, 0L).map((x:T) => doSomething(x))


                     fly.read(template, 0L).map(doSomething(_))


                                                                                           http://www.casualmiracles.com/




do nothing for none - verbose to use pattern matching
(x:T) => doSomething(x) is a first class function
ASIDE

Options can be implemented in other languages

Clumsy in Java but still useful

An experiment:

    Problems exposed where null was not expected

    Clarify business logic and behaviour


                                           http://www.casualmiracles.com/
IDIOMS - RETURN VALUES
                     int iterations = 10000;
                     if (args.length > 0) iterations = Integer.parseInt(args[0]);


                     val iterations = if (args.length > 0) args(0).toInt else 10000

                     def urlFor(path: String) =
                        try {
                           new URL(path)
                        } catch {
                           case e: MalformedURLException => new URL("http://www.scala-lang.org")
                        }




                                                                                         http://www.casualmiracles.com/




pattern matching for exceptions
exceptions are runtime
IDIOMS - FILTERING
                       public Collection<FlyServerRep> getMatchingReps(String [] tags) {
                             Collection matched = new ArrayList<FlyServerRep>();
                             for (FlyServerRep rep : reps.values()) {
                                if (rep.tagsMatch(tags)) {
                                       matched.add(rep);
                                }
                             }
                             return matched;
                         }


                       def getMatchingReps(tags:Array[String]):Collection[FlyServerRep]
                        = reps.values.filter((rep:FlyServerRep) => rep.tagsMatch(tags)).toList


                       def getMatchingReps(tags:Array[String]):Collection[FlyServerRep]
                        = reps.values.filter(_.tagsMatch(tags)).toList


                                                                                                http://www.casualmiracles.com/




filter items from a collection
IDIOMS - COMPREHENSIONS
                       public StatsBean[] getStatsArray(DataInputStream dis) throws IOException {
                         long statsCount = dis.readLong();
                         StatsBean [] stats = new StatsBean[(int)statsCount];
                         for (int i = 0; i < statsCount; i++) {
                             stats[i] = StatsBean.makeBeanFromStream(dis);
                         }
                         return stats;
                      }




                      def getStats(dis: DataInputStream): Seq[StatsBean] =
                         for (i <- 0 until dis.readLong().toInt) yield StatsBean.makeBeanFromStream(dis)




                                                                                               http://www.casualmiracles.com/




Create an array of items
for comprehension - iterate over something collecting results of the
expression after yield
FOR COMPREHENSION

                     Syntax: for ( seq ) yield e

                     Where seq is a sequence of generators, definitions and filters

                     e evaluated for each binding of generators and definitions

                     Return a sequence of evaluated values




                                                                   http://www.casualmiracles.com/




generator— roughly speaking, an expression that pulls an item from a
collection
easier to show an example...
FOR COMPREHENSION

                     val names = for {

                       p <- persons // a generator

                       n = p.name // a definition

                       if (n startsWith "To") // a filter

                     } yield n


                                                           http://www.casualmiracles.com/




p bound to each item in persons
IDIOMS - FOLD
                      /**
                      * @return the lease of the last entry written
                      */
                      public long writeMany(Collection entries, long lease) {
                         long lastLease = 0;
                         for (Object entry : entries) {
                            lastLease = codec.write( entry, lease );
                         }
                         return lastLease;
                      }



                      def writeMany(entries: Collection[AnyRef], lease: Long): Long
                           = (0L /: entries){(previousLease, nextEntry) => codec.write(nextEntry, lease)}




                                                                                               http://www.casualmiracles.com/




method writes entries to the space and returns the lease of the last item
written
function takes two parameters, ignores previousLease, returns the result of
codec.write
good use of fold?
IDIOMS - ACCESSORS
                    public class FlyServerRep {                           class FlyServerRep(var flyAddr:InetAddress, var flyTags:Array[String])

                        private String [] flyTags;
                        private InetAddress flyAddr;

                        FlyServerRep(InetAddress addr, String[] tags) {
                           flyAddr = addr;
                           flyTags = tags;
                        }

                        public String[] getFlyTags() {
                          return flyTags;
                        }

                        public void setFlyTags(String[] flyTags) {
                          this.flyTags = flyTags;
                        }

                        public InetAddress getFlyAddr() {
                          return flyAddr;
                        }

                        public void setFlyAddr(InetAddress flyAddr) {
                          this.flyAddr = flyAddr;
                        }
                    }
                                                                                                                  http://www.casualmiracles.com/




var on constructor parameters, scala generates accessor methods: x and x_
IDIOMS - FUNCTIONS
public Object read(Object template, long timeout) {       public Object take(Object template, long timeout) {
  Object ret = codec.read(template, 0);                     Object ret = codec.take(template, 0);
  ....                                                      ....
  while(...)                                                while(...)
       ret = codec.read(template, 0);                            ret = codec.take(template, 0);




  def read[T <: AnyRef](template: T, timeout: Long): Option[T] = retrieve(template, timeout, codec.read)
  def take[T <: AnyRef](template: T, timeout: Long): Option[T] = retrieve(template, timeout, codec.take)

  private def retrieve[T](template: T, timeout: Long, m: (T, Long) => Option[T]): Option[T] = {
     var ret = m(template, 0L)
     ....
     while(...)
          ret = m(template, 0)




                                                                                     http://www.casualmiracles.com/
CONTROL ABSTRACTION
System.out.println("Processing " + iterations + " writes and reads");
long start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
   space.write(object, 1000);
   space.read(template, 0L);
}
long end = System.currentTimeMillis();
float timeInSeconds = (float) (end - start) / 1000.0f;
System.out.println("Which took " + timeInSeconds + " secondsn");




                                                                        http://www.casualmiracles.com/
CONTROL ABSTRACTION
                     Time("Processing " + iterations + " writes and takes", iterations) {
                        space.write(obj, 1000)
                        space.take(template, 0L)
                     }



                     object Time {
                      def apply(name: String, iterations: Int)(block: => Unit): Unit = {
                        println(name)
                        val start = System.currentTimeMillis()

                             for (i <- 0 until iterations) block

                             val end = System.currentTimeMillis()
                             val timeInSeconds = (end - start) / 1000.0F
                             println("Completed in " + timeInSeconds + " secondsn")
                         }
                     }


                                                                                            http://www.casualmiracles.com/




apply methods have special meaning - invoked using a method-less
expression
eg Time (... is the same as Time.apply(...
CONTROL ABSTRACTION
trait NotiFly extends FlyPrime {
  def notifyWrite(template: AnyRef, leaseTime: Long)(block: => Unit): Boolean
}



fly.notifyWrite(template, LEASE){
  println("Block Template matched!")
}




                                                                        http://www.casualmiracles.com/
ACTORS

Scala’s primary concurrency construct

Concurrent processes communicating by exchanging messages

Scala Actor implementation is a library - several of them




                                               http://www.casualmiracles.com/
ACTORS
trait NotiFly extends FlyPrime {
  def notifyWrite(template: AnyRef, leaseTime: Long, actor: Actor): Boolean
}



import scala.actors.Actor._
val myActor = actor { // factory method taking a block
     loop {             // we want the actor to keep processing messages
       react {          // handle messages
         case FlyPrime.ACTOR_MESSAGE => println("Actor received a message!")
       }
     }
   }


fly.notifyWrite(template, LEASE, myActor)



                                                                         http://www.casualmiracles.com/
JAVA TO SCALA COMPARED
 Java   has 1556 LoC, Scala has 934 LoC => 60%

 Core    code is about half the size

 Why?

    Most algorithms can be characterised as Searching, Sorting, Filtering,
     Mapping, Combining, Counting (Peter Norvig)

    Scala and functional languages provide good abstractions for these

 Java   is 2% faster

    Need more comprehensive tests to find out why
                                                            http://www.casualmiracles.com/
WHAT NEXT?
 Scala   2.8

    Port from 2.7.7 complete

    Available for 2.8 soon

 Implement     the library from scratch?

    Design of existing library is the same as the Java library

    Current version made improvements in the small

    Perhaps a more functional approach would be better?
                                                              http://www.casualmiracles.com/
>
                             <----
                           --------->
                             <----
                               >




                    FROM JAVA TO SCALA




                                        http://www.casualmiracles.com/




2/3 lines of code
could be better

More Related Content

What's hot

Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングscalaconfjp
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
iOS 5 & Xcode 4: ARC, Stroryboards
iOS 5 & Xcode 4: ARC, StroryboardsiOS 5 & Xcode 4: ARC, Stroryboards
iOS 5 & Xcode 4: ARC, StroryboardsEungShik (Henry) Kim
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaMatthias Noback
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Charles Nutter
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightGiuseppe Arici
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011Charles Nutter
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Webnickmbailey
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...
MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...
MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...MMT - Multimediatreff
 
Mario heiderich. got your nose! how to steal your precious data without using...
Mario heiderich. got your nose! how to steal your precious data without using...Mario heiderich. got your nose! how to steal your precious data without using...
Mario heiderich. got your nose! how to steal your precious data without using...Yury Chemerkin
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292ytoshima
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015Charles Nutter
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
Solr Anti-Patterns: Presented by Rafał Kuć, Sematext
Solr Anti-Patterns: Presented by Rafał Kuć, SematextSolr Anti-Patterns: Presented by Rafał Kuć, Sematext
Solr Anti-Patterns: Presented by Rafał Kuć, SematextLucidworks
 

What's hot (20)

Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
 
Dispatch in Clojure
Dispatch in ClojureDispatch in Clojure
Dispatch in Clojure
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
iOS 5 & Xcode 4: ARC, Stroryboards
iOS 5 & Xcode 4: ARC, StroryboardsiOS 5 & Xcode 4: ARC, Stroryboards
iOS 5 & Xcode 4: ARC, Stroryboards
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Barcelona
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Web
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...
MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...
MMT 29: "Hab Dich!" -- Wie Angreifer ganz ohne JavaScript an Deine wertvollen...
 
Mario heiderich. got your nose! how to steal your precious data without using...
Mario heiderich. got your nose! how to steal your precious data without using...Mario heiderich. got your nose! how to steal your precious data without using...
Mario heiderich. got your nose! how to steal your precious data without using...
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292
 
Runtime
RuntimeRuntime
Runtime
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
Solr Anti-Patterns: Presented by Rafał Kuć, Sematext
Solr Anti-Patterns: Presented by Rafał Kuć, SematextSolr Anti-Patterns: Presented by Rafał Kuć, Sematext
Solr Anti-Patterns: Presented by Rafał Kuć, Sematext
 

Similar to Porting Java To Scala

Take Flight - Using Fly with the Play Framework
Take Flight - Using Fly with the Play FrameworkTake Flight - Using Fly with the Play Framework
Take Flight - Using Fly with the Play FrameworkAsher Glynn
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Immutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaAOE
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Codemotion
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in ScalaAlex Payne
 
Clojutre Real Life (2012 ClojuTRE Retro Edition)
Clojutre Real Life (2012 ClojuTRE Retro Edition)Clojutre Real Life (2012 ClojuTRE Retro Edition)
Clojutre Real Life (2012 ClojuTRE Retro Edition)Metosin Oy
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonLuciano Mammino
 
TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011bobmcwhirter
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSimonPilkington8
 

Similar to Porting Java To Scala (20)

Take Flight - Using Fly with the Play Framework
Take Flight - Using Fly with the Play FrameworkTake Flight - Using Fly with the Play Framework
Take Flight - Using Fly with the Play Framework
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Immutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS Lambda
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in Scala
 
Clojutre Real Life (2012 ClojuTRE Retro Edition)
Clojutre Real Life (2012 ClojuTRE Retro Edition)Clojutre Real Life (2012 ClojuTRE Retro Edition)
Clojutre Real Life (2012 ClojuTRE Retro Edition)
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Java Intro
Java IntroJava Intro
Java Intro
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
 
TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS Technologies
 
Scala
ScalaScala
Scala
 

Recently uploaded

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 

Recently uploaded (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 

Porting Java To Scala

  • 1. > <---- ---------> <---- > DEVELOPING THE SCALA BINDINGS FOR THE FLY OBJECT SPACE Channing Walton Nigel Warren channing.walton@casualmiracles.com nige@zink-digital.com http://www.casualmiracles.com/ CM, Java experience, CRE, UCL Presentation about my experience porting from Java to Scala
  • 2. INTRODUCTION State safe co-ordination and communication between distributed system components. http://www.casualmiracles.com/
  • 3. SPACES Tuple Spaces - Linda (a coordination language) in - put a tuple into a space rd – get a copy of a tuple from the space out – remove tuple from the space Subsequently … Java Spaces - Jini – Java Rinda – Ruby PyLinda – Python etc., etc. http://www.casualmiracles.com/
  • 4. FLY Fly is an ‘Object Space’ Network wide - Object level - Storage and Matching Matching – by Object Templates Object Serialisation – Native to a language or language neutural Leasing – Information and resources have prescribed lifetimes http://www.casualmiracles.com/
  • 5. FLY PRIME INTERFACE public interface FlyPrime { long write(Object entry, long leaseTime); Object read(Object template, long waitTime); Object take(Object template, long waitTime); } http://www.casualmiracles.com/
  • 6. DESIGN DIAMOND Minimise Interface Complexity Minimise Uses http://www.casualmiracles.com/
  • 7. FLY SPACE DESIGN Minimal But Complete Interface Write Read Take Threading Object Locking Distribution Matching Expiring Pthreads Minimal Use of Sockets OS interfaces Malloc - Free http://www.casualmiracles.com/
  • 8. FLY SPACE INTERFACE HIERARCHY Fly MultiFly NotiFly writeMany notifyWrite readMany notifyTake takeMany FlyPrime write read take http://www.casualmiracles.com/
  • 9. FLY SCALA Scala Application Scala Application Client Client Scala Space Scala Space Interface Interface Scala Binding Scala Binding Fly Server http://www.casualmiracles.com/
  • 10. FROM JAVA TO SCALA • Syntactic Conversion • Idiomatic API • Idioms Internally • Actors • Java and Scala Compared • What Next? http://www.casualmiracles.com/
  • 11. SYNTACTIC public interface NotiFly extends FlyPrime { boolean notifyWrite(Object template, NotifyHandler handler, long leaseTime); boolean notifyTake(Object template, NotifyHandler handler, long leaseTime); } trait NotiFly extends FlyPrime { def notifyWrite(template: AnyRef, handler: NotifyHandler, leaseTime: Long): Boolean def notifyTake(template:AnyRef, handler:NotifyHandler, leaseTime:Long):Boolean } http://www.casualmiracles.com/
  • 12. SYNTACTIC public static void main(String[] args) throws Exception { def main(args: Array[String]) { FileInputStream f = new FileInputStream(new File(args[0])); val f = new FileInputStream(new File(args(0))); DataInputStream dis = new DataInputStream(f); val dis = new DataInputStream(f); StatsDecoder decoder = new StatsDecoder(); val decoder = new StatsDecoder(); long time = dis.readLong(); var time = dis.readLong(); while ( true ) { while (true) { int size = dis.readInt(); val size = dis.readInt(); StatsBean [] beans = decoder.getStatsArray(dis); val beans = decoder.getStats(dis); Stats.writeStats(beans); StatsPrinter.writeStats(beans); System.out.println("--------------"); System.out.println("--------------"); long nextTime = dis.readLong(); val nextTime = dis.readLong(); Thread.sleep(nextTime-time); Thread.sleep(nextTime - time); time = nextTime; time = nextTime; } } } } http://www.casualmiracles.com/
  • 13. IDIOMS - OPTION An Option represents an optional value Two subclasses: Some and None Java has … null http://www.casualmiracles.com/ Experiment with Options in Java later
  • 14. IDIOMS - OPTION trait FlyPrime { def read[T <: AnyRef](template: T, waitTime: Long): Option[T] } fly.read(template, 0L) match { case None => { println("No ball in play") serveBall(fly) println("Served Ball - Please start a Pong") } case Some(gameBall) => { println("Received ball - game on!") returnBall(fly, gameBall) } } http://www.casualmiracles.com/ pattern matching - scala can extract values from the matching pattern - Some(ball) no types
  • 15. IDIOMS - OPTION trait FlyPrime { def read[T <: AnyRef](template: T, waitTime: Long): Option[T] } fly.read(template, 0L) match { case None => // do nothing case Some(gameBall) => doSomething(gameBall) } fly.read(template, 0L).map((x:T) => doSomething(x)) fly.read(template, 0L).map(doSomething(_)) http://www.casualmiracles.com/ do nothing for none - verbose to use pattern matching (x:T) => doSomething(x) is a first class function
  • 16. ASIDE Options can be implemented in other languages Clumsy in Java but still useful An experiment: Problems exposed where null was not expected Clarify business logic and behaviour http://www.casualmiracles.com/
  • 17. IDIOMS - RETURN VALUES int iterations = 10000; if (args.length > 0) iterations = Integer.parseInt(args[0]); val iterations = if (args.length > 0) args(0).toInt else 10000 def urlFor(path: String) = try { new URL(path) } catch { case e: MalformedURLException => new URL("http://www.scala-lang.org") } http://www.casualmiracles.com/ pattern matching for exceptions exceptions are runtime
  • 18. IDIOMS - FILTERING public Collection<FlyServerRep> getMatchingReps(String [] tags) { Collection matched = new ArrayList<FlyServerRep>(); for (FlyServerRep rep : reps.values()) { if (rep.tagsMatch(tags)) { matched.add(rep); } } return matched; } def getMatchingReps(tags:Array[String]):Collection[FlyServerRep] = reps.values.filter((rep:FlyServerRep) => rep.tagsMatch(tags)).toList def getMatchingReps(tags:Array[String]):Collection[FlyServerRep] = reps.values.filter(_.tagsMatch(tags)).toList http://www.casualmiracles.com/ filter items from a collection
  • 19. IDIOMS - COMPREHENSIONS public StatsBean[] getStatsArray(DataInputStream dis) throws IOException { long statsCount = dis.readLong(); StatsBean [] stats = new StatsBean[(int)statsCount]; for (int i = 0; i < statsCount; i++) { stats[i] = StatsBean.makeBeanFromStream(dis); } return stats; } def getStats(dis: DataInputStream): Seq[StatsBean] = for (i <- 0 until dis.readLong().toInt) yield StatsBean.makeBeanFromStream(dis) http://www.casualmiracles.com/ Create an array of items for comprehension - iterate over something collecting results of the expression after yield
  • 20. FOR COMPREHENSION Syntax: for ( seq ) yield e Where seq is a sequence of generators, definitions and filters e evaluated for each binding of generators and definitions Return a sequence of evaluated values http://www.casualmiracles.com/ generator— roughly speaking, an expression that pulls an item from a collection easier to show an example...
  • 21. FOR COMPREHENSION val names = for { p <- persons // a generator n = p.name // a definition if (n startsWith "To") // a filter } yield n http://www.casualmiracles.com/ p bound to each item in persons
  • 22. IDIOMS - FOLD /** * @return the lease of the last entry written */ public long writeMany(Collection entries, long lease) { long lastLease = 0; for (Object entry : entries) { lastLease = codec.write( entry, lease ); } return lastLease; } def writeMany(entries: Collection[AnyRef], lease: Long): Long = (0L /: entries){(previousLease, nextEntry) => codec.write(nextEntry, lease)} http://www.casualmiracles.com/ method writes entries to the space and returns the lease of the last item written function takes two parameters, ignores previousLease, returns the result of codec.write good use of fold?
  • 23. IDIOMS - ACCESSORS public class FlyServerRep { class FlyServerRep(var flyAddr:InetAddress, var flyTags:Array[String]) private String [] flyTags; private InetAddress flyAddr; FlyServerRep(InetAddress addr, String[] tags) { flyAddr = addr; flyTags = tags; } public String[] getFlyTags() { return flyTags; } public void setFlyTags(String[] flyTags) { this.flyTags = flyTags; } public InetAddress getFlyAddr() { return flyAddr; } public void setFlyAddr(InetAddress flyAddr) { this.flyAddr = flyAddr; } } http://www.casualmiracles.com/ var on constructor parameters, scala generates accessor methods: x and x_
  • 24. IDIOMS - FUNCTIONS public Object read(Object template, long timeout) { public Object take(Object template, long timeout) { Object ret = codec.read(template, 0); Object ret = codec.take(template, 0); .... .... while(...) while(...) ret = codec.read(template, 0); ret = codec.take(template, 0); def read[T <: AnyRef](template: T, timeout: Long): Option[T] = retrieve(template, timeout, codec.read) def take[T <: AnyRef](template: T, timeout: Long): Option[T] = retrieve(template, timeout, codec.take) private def retrieve[T](template: T, timeout: Long, m: (T, Long) => Option[T]): Option[T] = { var ret = m(template, 0L) .... while(...) ret = m(template, 0) http://www.casualmiracles.com/
  • 25. CONTROL ABSTRACTION System.out.println("Processing " + iterations + " writes and reads"); long start = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { space.write(object, 1000); space.read(template, 0L); } long end = System.currentTimeMillis(); float timeInSeconds = (float) (end - start) / 1000.0f; System.out.println("Which took " + timeInSeconds + " secondsn"); http://www.casualmiracles.com/
  • 26. CONTROL ABSTRACTION Time("Processing " + iterations + " writes and takes", iterations) { space.write(obj, 1000) space.take(template, 0L) } object Time { def apply(name: String, iterations: Int)(block: => Unit): Unit = { println(name) val start = System.currentTimeMillis() for (i <- 0 until iterations) block val end = System.currentTimeMillis() val timeInSeconds = (end - start) / 1000.0F println("Completed in " + timeInSeconds + " secondsn") } } http://www.casualmiracles.com/ apply methods have special meaning - invoked using a method-less expression eg Time (... is the same as Time.apply(...
  • 27. CONTROL ABSTRACTION trait NotiFly extends FlyPrime { def notifyWrite(template: AnyRef, leaseTime: Long)(block: => Unit): Boolean } fly.notifyWrite(template, LEASE){ println("Block Template matched!") } http://www.casualmiracles.com/
  • 28. ACTORS Scala’s primary concurrency construct Concurrent processes communicating by exchanging messages Scala Actor implementation is a library - several of them http://www.casualmiracles.com/
  • 29. ACTORS trait NotiFly extends FlyPrime { def notifyWrite(template: AnyRef, leaseTime: Long, actor: Actor): Boolean } import scala.actors.Actor._ val myActor = actor { // factory method taking a block loop { // we want the actor to keep processing messages react { // handle messages case FlyPrime.ACTOR_MESSAGE => println("Actor received a message!") } } } fly.notifyWrite(template, LEASE, myActor) http://www.casualmiracles.com/
  • 30. JAVA TO SCALA COMPARED  Java has 1556 LoC, Scala has 934 LoC => 60%  Core code is about half the size  Why?  Most algorithms can be characterised as Searching, Sorting, Filtering, Mapping, Combining, Counting (Peter Norvig)  Scala and functional languages provide good abstractions for these  Java is 2% faster  Need more comprehensive tests to find out why http://www.casualmiracles.com/
  • 31. WHAT NEXT?  Scala 2.8  Port from 2.7.7 complete  Available for 2.8 soon  Implement the library from scratch?  Design of existing library is the same as the Java library  Current version made improvements in the small  Perhaps a more functional approach would be better? http://www.casualmiracles.com/
  • 32. > <---- ---------> <---- > FROM JAVA TO SCALA http://www.casualmiracles.com/ 2/3 lines of code could be better