SlideShare a Scribd company logo
1 of 30
Download to read offline
by Massimiliano Dessì
desmax74@yahoo.com
twitter: @desmax74

and Mario Fusco
mario.fusco@gmail.com
twitter: @mariofusco
Moore's
  law
Now achieved
by increasing
 the number
   of cores


 The number of transistors on integrated
 circuits doubles approximately every two years
Moore's
  law
Now achieved
by increasing
 the number
   of cores


 The number of transistors on integrated
 circuits doubles approximately every two years
Amdahl's
                                      law



The speedup of a program using multiple processors
 in parallel computing is limited by the time needed
      for the sequential fraction of the program
Concurrency & Parallelism
Concurrent programming
Managing concurrent requests




                               Parallel programming
                               Running multiple tasks at
                                   the same time


                Both are too hard!
The cause of the problem …

                  Mutable state +
              Parallel processing =
              Non-determinism
The cause of the problem …

                  Mutable state +
              Parallel processing =
              Non-determinism


                Functional
               Programming
… and its effects



Race conditions
                                      Starvation

 Deadlocks
                                          Livelocks
… and its effects



Race conditions
                                      Starvation

 Deadlocks
                                          Livelocks




    Too hard to think about them!
The native Java concurrency model
   Based on:                      Threads

                                            Semaphores




         Locks                                        Synchronization


They are sometimes plain evil …

                 … and sometimes a necessary pain …

                                       … but always the wrong   default
Different concurrency models



Shared mutable state
  (threads + locks)




                                     Isolated mutable state (actors)


                       Purely immutable (pure functions)
Summing attendants ages (Threads)
class Blackboard {
    int sum = 0;
    int read() { return sum; }
    void write(int value) { sum = value; }
}


                 class Attendant implements Runnable {
                     int age;
                     Blackboard blackboard;

                     public void run() {
                         synchronized(blackboard) {
                             int oldSum = blackboard.read();
                             int newSum = oldSum + age;
                             blackboard.write(newSum);
                         }
                     }
                 }
Summing attendants ages (Actors)
class Blackboard extends UntypedActors {
    int sum = 0;
    public void onReceive(Object message) {
        if (message instanceof Integer) {
            sum += (Integer)message;
        }
    }
}
                          class Attendant {
                              int age;
                              Blackboard blackboard;

                              public void sendAge() {
                                  blackboard.sendOneWay(age);
                              }
                          }
Summing attendants ages (Functional)
class Blackboard {
    final int sum;
    Blackboard(int sum) { this.sum = sum; }
}


class Attendant {
    int age;
    Attendant next;

    public Blackboard addMyAge(Blackboard blackboard) {
        final Blackboard b = new Blackboard(blackboard.sum + age);
        return next == null ? b : next.myAge(b);
    }
}

attendants.foldLeft(new Blackboard(0),
                    (att, b) -> new Blackboard(b.sum + att.age));
What is a functional program?
A program created using only pure functions
No side effects allowed like:
  Reassigning a variable
  Modifying a data structure in place
  Setting a field on an object
                                              }
  Throwing an exception or halting with an error



                                              }
  Printing to the console
  Reading user input
  Reading from or writing to a file
  Drawing on the screen
Functional programming is a restriction on how we
  write programs, but not on what they can do
The OOP/FP dualism
class Bird    OOP vs. …
class Cat {
  def capture(b: Bird): Unit = ...
  def eat(): Unit = ...
}
val cat = new Cat
val bird = new Bird

cat.capture(bird)
cat.eat()
             class Cat
             class Bird
             trait Catch
                             … FP                The story
             trait FullStomach
             def capture(prey: Bird, hunter: Cat): Cat with Catch
             def eat(consumer: Cat with Catch): Cat with FullStomach

             val story = (capture _) andThen (eat _)
             story(new Bird, new Cat)
What is a (pure) function?
A function with input type A and output type B
is a computation which relates every value a of
  type A to exactly one value b of type B such
  that b is determined solely by the value of a




                                  But, if it really is a
                                  function, it will do
                                     nothing else
Referential transparency
An expression e is referentially transparent if for all programs p,
    all occurrences of e in p can be replaced by the result of
 evaluating e, without affecting the observable behavior of p




   A function f is pure if the expression f(x) is referentially
        transparent for all referentially transparent x
RT
String x = "purple";
String r1 = x.replace('p', 't');
String r2 = x.replace('p', 't');
                                                  vs.
String r1 = "purple".replace('p', 't');
    r1: "turtle"
String r2 = "purple".replace('p', 't');
    r2: "turtle"
                                          Non-RT
Immutable            StringBuilder x = new StringBuilder("Hi");
                     StringBuilder y = x.append(", mom");
                     String r1 = y.toString();
      Mutable        String r2 = y.toString();

                     String r1 = x.append(", mom").toString();
 Expression not          r1: "Hi, mom"
replaceable with     String r2 = x.append(", mom").toString();
                         r1: "Hi, mom, mom"
    its result
RT wins

Under a developer point of view:
   Easier to reason about since effects of evaluation are
   purely local
   Use of the substitution model: it's possible to replace a
   term with an equivalent one

Under a performance point of view:
   The JVM is free to optimize the code by safely
   reordering the instructions
   No need to synchronize access to shared data
Immutability

Immutable objects can be shared among
many threads exactly because none of
them can modify it

In the same way immutable (persistent)
data structures can be shared without any
need to synchronize the different threads
accessing them
Persistent Collections



                     5



     3                               8


 E           4               7               9



         E       E       E       E       E       E
Persistent Collections



                         5


2
         3                               8


     E           4               7               9



             E       E       E       E       E       E
Persistent Collections
                                 5



                 3
                                     5


    2
                     3                               8

E       E
             E               4               7               9



                         E       E       E       E       E       E
Persistent Collections
                                  5     New Root


                 3           Old Root
                                       5


    2
                     3                                 8
                                  Shared data
E       E
             E                4                7               9



                         E         E       E       E       E       E
Modularity
class Player {
    String name;   public void declareWinner(Player p) {
    int score;         System.out.println(p.name + " wins!");
}                  }
                   public void winner(Player p1, Player p2) {
                       if (p1.score > p2.score) declareWinner(p1)
                       else declareWinner(p2);
                   }
Modularity
class Player {
    String name;   public void declareWinner(Player p) {
    int score;         System.out.println(p.name + " wins!");
}                  }
                   public void winner(Player p1, Player p2) {
                       if (p1.score > p2.score) declareWinner(p1)
                       else declareWinner(p2);
                   }
                                                      Separate
                                                 computational logic
public Player maxScore(Player p1, Player p2) {    from side effects
    return p1.score > p2.score ? p1 : p2;
}
public void winner(Player p1, Player p2) {
    declareWinner(maxScore(p1, p2));
}
Modularity
class Player {
    String name;   public void declareWinner(Player p) {
    int score;         System.out.println(p.name + " wins!");
}                  }
                   public void winner(Player p1, Player p2) {
                       if (p1.score > p2.score) declareWinner(p1)
                       else declareWinner(p2);
                   }
                                                      Separate
                                                 computational logic
public Player maxScore(Player p1, Player p2) {    from side effects
    return p1.score > p2.score ? p1 : p2;
}
public void winner(Player p1, Player p2) {
    declareWinner(maxScore(p1, p2));
}
          declareWinner(players.reduceLeft(maxScore))

 reuse maxScore to compute the winner among a list of players
Modularity
class Player {
    String name;    public void declareWinner(Player p) {
    int score;          System.out.println(p.name + " wins!");
}                   }
                    public void winner(Player p1, Player p2) {
                        if (p1.score > p2.score) declareWinner(p1)
                        else declareWinner(p2);
                    }
                                                           Separate
                                                      computational logic
public Player maxScore(Player p1, Player p2) {         from side effects
    return p1.score > p2.score ? p1 : p2;
}
public void winner(Player p1, Player p2) {
    declareWinner(maxScore(p1, p2));
}
declareWinner(players.parallel().reduceLeft(maxScore))

       It's trivial to parallelize "internal" iteration
A pure functional core



                            functional
                               core




Any function with side-effects can be split into a pure function at the
core and a pair of functions with side-effect. This transformation can
be repeated to push side-effects to the outer layers of the program.

More Related Content

What's hot

Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!José Paumard
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVMMario Fusco
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1Dhaval Dalal
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8JavaDayUA
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 

What's hot (20)

Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
Kotlin
KotlinKotlin
Kotlin
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Lezione03
Lezione03Lezione03
Lezione03
 

Viewers also liked

If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageMario Fusco
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep diveMario Fusco
 
Arabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooq
Arabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooqArabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooq
Arabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooqLucidworks
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing DroolsMario Fusco
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 

Viewers also liked (16)

If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
Arabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooq
Arabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooqArabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooq
Arabic Content with Apache Solr: Presented by Ramzi Alqrainy, OpenSooq
 
Seven Deadly Sins
Seven Deadly Sins Seven Deadly Sins
Seven Deadly Sins
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 

Similar to Why we cannot ignore Functional Programming

Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle ScalaSlim Ouertani
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.Brian Hsu
 
Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)chk49
 
LISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love ParanthesesLISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love ParanthesesDominic Graefen
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
Persistent Data Structures by @aradzie
Persistent Data Structures by @aradziePersistent Data Structures by @aradzie
Persistent Data Structures by @aradzieVasil Remeniuk
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Coen De Roover
 
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Codemotion
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its toolsMax Andersen
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developersbrweber2
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talkJohn Stevenson
 
Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011Devnology
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsMiquel Martin
 

Similar to Why we cannot ignore Functional Programming (20)

Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Java
JavaJava
Java
 
Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)Virtual Separation of Concerns (2011 Update)
Virtual Separation of Concerns (2011 Update)
 
Clojure
ClojureClojure
Clojure
 
LISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love ParanthesesLISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love Parantheses
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Persistent Data Structures by @aradzie
Persistent Data Structures by @aradziePersistent Data Structures by @aradzie
Persistent Data Structures by @aradzie
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012
 
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
 
Scilab vs matlab
Scilab vs matlabScilab vs matlab
Scilab vs matlab
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its tools
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talk
 
Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011Devnology Workshop Genpro 2 feb 2011
Devnology Workshop Genpro 2 feb 2011
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

Why we cannot ignore Functional Programming

  • 1. by Massimiliano Dessì desmax74@yahoo.com twitter: @desmax74 and Mario Fusco mario.fusco@gmail.com twitter: @mariofusco
  • 2. Moore's law Now achieved by increasing the number of cores The number of transistors on integrated circuits doubles approximately every two years
  • 3. Moore's law Now achieved by increasing the number of cores The number of transistors on integrated circuits doubles approximately every two years
  • 4. Amdahl's law The speedup of a program using multiple processors in parallel computing is limited by the time needed for the sequential fraction of the program
  • 5. Concurrency & Parallelism Concurrent programming Managing concurrent requests Parallel programming Running multiple tasks at the same time Both are too hard!
  • 6. The cause of the problem … Mutable state + Parallel processing = Non-determinism
  • 7. The cause of the problem … Mutable state + Parallel processing = Non-determinism Functional Programming
  • 8. … and its effects Race conditions Starvation Deadlocks Livelocks
  • 9. … and its effects Race conditions Starvation Deadlocks Livelocks Too hard to think about them!
  • 10. The native Java concurrency model Based on: Threads Semaphores Locks Synchronization They are sometimes plain evil … … and sometimes a necessary pain … … but always the wrong default
  • 11. Different concurrency models Shared mutable state (threads + locks) Isolated mutable state (actors) Purely immutable (pure functions)
  • 12. Summing attendants ages (Threads) class Blackboard { int sum = 0; int read() { return sum; } void write(int value) { sum = value; } } class Attendant implements Runnable { int age; Blackboard blackboard; public void run() { synchronized(blackboard) { int oldSum = blackboard.read(); int newSum = oldSum + age; blackboard.write(newSum); } } }
  • 13. Summing attendants ages (Actors) class Blackboard extends UntypedActors { int sum = 0; public void onReceive(Object message) { if (message instanceof Integer) { sum += (Integer)message; } } } class Attendant { int age; Blackboard blackboard; public void sendAge() { blackboard.sendOneWay(age); } }
  • 14. Summing attendants ages (Functional) class Blackboard { final int sum; Blackboard(int sum) { this.sum = sum; } } class Attendant { int age; Attendant next; public Blackboard addMyAge(Blackboard blackboard) { final Blackboard b = new Blackboard(blackboard.sum + age); return next == null ? b : next.myAge(b); } } attendants.foldLeft(new Blackboard(0), (att, b) -> new Blackboard(b.sum + att.age));
  • 15. What is a functional program? A program created using only pure functions No side effects allowed like: Reassigning a variable Modifying a data structure in place Setting a field on an object } Throwing an exception or halting with an error } Printing to the console Reading user input Reading from or writing to a file Drawing on the screen Functional programming is a restriction on how we write programs, but not on what they can do
  • 16. The OOP/FP dualism class Bird OOP vs. … class Cat { def capture(b: Bird): Unit = ... def eat(): Unit = ... } val cat = new Cat val bird = new Bird cat.capture(bird) cat.eat() class Cat class Bird trait Catch … FP The story trait FullStomach def capture(prey: Bird, hunter: Cat): Cat with Catch def eat(consumer: Cat with Catch): Cat with FullStomach val story = (capture _) andThen (eat _) story(new Bird, new Cat)
  • 17. What is a (pure) function? A function with input type A and output type B is a computation which relates every value a of type A to exactly one value b of type B such that b is determined solely by the value of a But, if it really is a function, it will do nothing else
  • 18. Referential transparency An expression e is referentially transparent if for all programs p, all occurrences of e in p can be replaced by the result of evaluating e, without affecting the observable behavior of p A function f is pure if the expression f(x) is referentially transparent for all referentially transparent x
  • 19. RT String x = "purple"; String r1 = x.replace('p', 't'); String r2 = x.replace('p', 't'); vs. String r1 = "purple".replace('p', 't'); r1: "turtle" String r2 = "purple".replace('p', 't'); r2: "turtle" Non-RT Immutable StringBuilder x = new StringBuilder("Hi"); StringBuilder y = x.append(", mom"); String r1 = y.toString(); Mutable String r2 = y.toString(); String r1 = x.append(", mom").toString(); Expression not r1: "Hi, mom" replaceable with String r2 = x.append(", mom").toString(); r1: "Hi, mom, mom" its result
  • 20. RT wins Under a developer point of view: Easier to reason about since effects of evaluation are purely local Use of the substitution model: it's possible to replace a term with an equivalent one Under a performance point of view: The JVM is free to optimize the code by safely reordering the instructions No need to synchronize access to shared data
  • 21. Immutability Immutable objects can be shared among many threads exactly because none of them can modify it In the same way immutable (persistent) data structures can be shared without any need to synchronize the different threads accessing them
  • 22. Persistent Collections 5 3 8 E 4 7 9 E E E E E E
  • 23. Persistent Collections 5 2 3 8 E 4 7 9 E E E E E E
  • 24. Persistent Collections 5 3 5 2 3 8 E E E 4 7 9 E E E E E E
  • 25. Persistent Collections 5 New Root 3 Old Root 5 2 3 8 Shared data E E E 4 7 9 E E E E E E
  • 26. Modularity class Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!"); } } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); }
  • 27. Modularity class Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!"); } } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logic public Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2; } public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2)); }
  • 28. Modularity class Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!"); } } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logic public Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2; } public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2)); } declareWinner(players.reduceLeft(maxScore)) reuse maxScore to compute the winner among a list of players
  • 29. Modularity class Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!"); } } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logic public Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2; } public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2)); } declareWinner(players.parallel().reduceLeft(maxScore)) It's trivial to parallelize "internal" iteration
  • 30. A pure functional core functional core Any function with side-effects can be split into a pure function at the core and a pair of functions with side-effect. This transformation can be repeated to push side-effects to the outer layers of the program.