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

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

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.