SlideShare une entreprise Scribd logo
1  sur  31
Erlang vs. Java
      January 19, 2011




    Artan Cami
(i)     Erlang history
(ii)    Erlang resources
(iii)   Java history
(iv)    Compare philosophies
(v)     Problem definition
(vi)    JEE approach & principles
(vii)   JEE solution details
(viii) Erlang/OTP approach & principles
(ix)    Erlang solution details
(x)     Erlang language basics
(xi)    Speculations
erlang history
                     http://www.erlang.org/course/history.html

1982-1985 telecom experiments with about 20 languages => need high symbolic language
1985-1986 experiments with Lisp, Prolog, Parlog... => need concurrency primitives and
error recovery => need new language
1987 first experiments with Erlang
1988 “Erlang escapes from the lab!”
1990 Erlang presented in ISS’90 => new users introduced
1992 Erlang ported to VxWorks, PC, Mac ...
1993 Distribution is added to Erlang => run homogeneous Erlang to heterogeneous
hardware
1997 OTP (open telecom platform) started
1998 Erlang banned => open source Erlang
2002 Concurrency Oriented Programming
2006 SMP (symmetric multiprocessing machine) Erlang - Multicore.
erlang resources
๏   Programming Erlang: Software for a Concurrent World - Joe Armstrong - Jul 2007

๏   ERLANG Programming - Francesco Cesarini, Simon Thompson - Jun 2009

๏   Erlang and OTP in Action - Martin Logan, Eric Merritt, Richard Carlson - Nov 2010

๏   www.erlang.org - Erlang Programming Language, Official Site

๏   www.trapexit.org - Erlang Community Site

๏   erlyweb.org - The Erlang Twist on Web Frameworks

๏   erlide.sourceforge.net - The Erlang IDE. Powered by Eclipse.

๏   www.infoq.com/interviews - interviews taken in Erlang Factory events.
java history
                       http://www.java.com/en/javahistory


1991 The Green Project begins
1992 “Oak”
1994 WebRunner - first browser for moving objects and executable content
1995 Oak becomes Java. Java technology released to a select group on wicked.neato.org
1996 JDKtm 1.0 released; first JavaOne conference
1997 Over 220,000 downloads of JDK 1.1 in just three weeks; JavaOne worlds largest
developer conference with over 8,000 attendees
1998 JDK 1.1 2 million downloads; Visa Java Smart Card; JCP formalized
1999 J2EE beta released; Java 2 source code released; over 20,000 people in JavaOne
2001 Over 2 million downloads of J2EE
2003 About 75% of professional developers use Java as their primary language
2004 Mars-Rover touches down on Mars; J2SE 5 (Tiger) released
2005 4.5 million java developers; 2.5 billion Java-enabled devices
philosophies/principles
• Java :
  •   “the computer is the network”
  •   write once, run anywhere
  •   simple
  •   concurrency multithreading
  •   object orientated programming

• Erlang :
  •   the world is parallel
  •   concurrent processes belong to the language - not OS
  •   very light weight concurrency
  •   share nothing; no mutable state; no locks
  •   pure asynchronous message passing
  •   “let it crash” - no defensive programming
  •   functional programming
bookstore problem
                        typical online bookstore



-       books: find books, display list of books, display the book details

    •      book details: book summary information, editorial reviews, product details,
           authors details, customer reviews, related books: frequently bought together,
           other books on this topic, other books by this author(s)

-       customer: create and maintain profile; store, find, and display transaction history.

-       orders: shopping cart capability; payment and shipment types; order placement.

-       non-functional requirements

➡       S - store app, B - books apps, C - customer apps; O - order apps
jee approach and patterns
• MVC
• Define layers: presentation, model, and data
• Model: EJB3 - stateless, stateful, singleton session beans;
  message-driven beans;
  •   container management, session facade, entity access object;

• ORM layer: JPA implementation
  •   EntityManager, entity POJOs;

• Pick a presentation framework: struts, jsf, templating, or
  portal
jee - deployment strategy
collocated          JVM 1

                      Applications


                         S           B   C   O



                    JVM 2

                      Applications
    Load Balancer

                            S        B   C   O



                    JVM 3

                      Applications


                            S        B   C   O
jee - deployment strategy
                       distributed
                                     JVM 2

                                      EJB Applications

                                             BEJB
 JVM 1

  Web Applications

                                     JVM 3
   SWEB      BWEB    CWEB   OWEB
                                       EJB Applications


                                             CEJB         OEJB
jee - books applications
 J V M 1                                         J V M 2
W e b C o n t a i n e r                      E J B C o n t a i n e r                            ORM

                                                                                        BookEntity


                                                               BookEAO EJB
                                                                               RelatedBooksEntity
    BooksController
                                              Books EJB                                         BookContentEntity


                                                                                 AuthorEntity
        BooksView                                           RelatedBookslEAO
                                                                   EJB
            BookDetailView
                      ...View
                                                                                    PublisherEntity
                           BookContentView
jee -customer applications
 J V M 1                          J V M 3
W e b C o n t a i n e r       E J B C o n t a i n e r                         ORM



                                                                       ProfileEntity
                                                 ProfileEAO EJB


    CustomerController                                            PaymentTypesEntity
                              Customer EJB


                                                                  OrdersHistoryEntity
  CustomerProfileView
                                               OrdersHistoryEAO
      ...View                                         EJB
          OrdersHisotryView
jee - orders applications
 J V M 1                          J V M 3
W e b C o n t a i n e r       E J B C o n t a i n e r                     ORM



          ShoppingCartContr                     ShoppingCartEAO   ShoppingCartEntity
                               ShoppingCart            EJB
                                   EJB

     OrdersController                                             PaymentEntity


                                                  PaymentsEAO
                                                                  ShippingEntity
                                                      EJB
   ShoppingCartView             Orders EJB

      ...View
           PaymentView                                                OrdersEntity
                                                  OrdersEAO
                                                     EJB
jee - sequence diagram
                                     display book details

BooksController           BooksEJB       BooksEAO RelatedBooksEAO
  1
         2
                                3
                                        4

                               5
                      7                                             BookView
                                                      6
                                                                               BookDetailView
                  8
                                                                          9
                                                                                        RelatedBooksView
                                                                                  10

                                                                          11

                                                                                            12
                                                                     13
 14
erlang/otp approach and
                patterns
• Use large number of processes in order to distribute/
  parallelize as much as possible;
  • process is the main building block with its own stack, garbage collection, message
  queue, security model.
  • message sending/receiving simplicity made possible by pattern matching and simple
  data structures;

• Avoid side effects - no shared resources among processes;
  • variables that don’t vary - single assignment. No mutable state, no shared memory, no
  locks;

• Small messages, big computations
• Distributed database Mnesia
• OTP patterns:
  • gen_server, event_handler, supervisor, application, ...
erlang - sequence & concurrency diagram
                  display book details

       BooksController               BooksDetailModel
            1     BooksDetailController
                      2
                                3
                                                    BookDetailView
                                     4

                                     5

                                                6
                          7


                                          RelatedBooksModel
                  RelatedBooksController
                      2’
                                3’
                                                 RelatedBooksView
                                     4’

                                     5’

                                                6’
                      7’

             8
erlang - books applications
                   Node 2



                      BooksDetails                BooksDetails
                         Model                       Model




     Node 1
                      BooksDetails                 RelatedBooks   RelatedBooks
                       Controller                   Controller        View
     BooksDetail
        View




                                      Books
                                     Controller
erlang - deployment strategy
                          Distributed
      Node 2                                  Node 3


             B                                    O                 C
          processes
                                                processes         processes




         Node 1

                                  OWEB
                      BWEB        processes           CWEB
                      processes
                                                      processes




                                   SWEB
                                  processes
erlang language basics

• Modules: .erl files ~ similar to .java files
  ‣   .beam is the compiled module extension ~ similar to .class in java
  ‣   -module(module_name). ~ similar to public class in java
  ‣   -export([list of public functions]). ~ similar to public
      method modifier in java
  ‣   -import(module,[list of public functions]). ~ similar to
      import in java
  ‣   other module attributes:
               -behaviour(otp behavior pattern name).
               -record(record_name, tuple).
               -compile(options).
erlang language basics


• Functions ~ similar to methods in java
  ‣   function_name( arguments ) -> function body.
  ‣   function body consists of instructions separated by commas
  ‣   one of the instructions results to the function output
  ‣   BIFs - build in functions
  ‣   function is called as module_name:function_name(arguments)
erlang language basics
• Processes
  ‣   the building blocks of concurrency
  ‣   simple to create;
      erlang:system_info(process_limit) 32,767

  ‣   simple primitives: spawn, send, receive:
      Pid = spawn(Node,Fun).
      Pid ! Message.

      receive ... end.

  ‣   Links, Exit signals, System processes
      spawn_link(Node,Fun) -> Pid

      process_flag(trap_exit,true).
      exit(Pid, Why)->true.

      erlang:monitor(process,Item)->MonitorRef

  ‣   Registered processes
  ‣   Independent stack, message queue, garbage collection
erlang language basics
• Messages
 ‣    asynchronous
 ‣    pass by copying
 ‣    lightweight and simple due to simple data structures
 ‣    selective receive due to pattern matching:


     loop(Name,Mod,OldState)->
     	 receive
     	 	 {From,{swap_code,NewMod}}->
     	 	 	 From!{Name,acknowledged},
     	 	 	 loop(Name,NewMod,OldState);
     	 	 {From,Request}->
     	 	 	 {Response,NewState}=Mod:handle(Request,OldState),
     	 	 	 From!{Name,Response},
     	 	 	 loop(Name,Mod,NewState)
     	 end.
erlang language basics
    • Terms
‣    Lists:
     Books = [Book1,Book2,Book3]
     Books = [Book1 | RestOfBooks]

     Book1 = {{isbn,”1-9343560-0-X”},{title,”Programming Erlang”},{authors,{“Joe
     Armstrong”}},{pages,515},{publisher,”The Pragmatic Programmer”}}

     Book2 = {{isbn,”9781933988788”},{title,”Erlang and OTP in Action”},
     {authors,{“Martin Logan”,”Eric Merritt”,”Richard Carlson”}},{pages,397},
     {publisher,”Manning”}}
     lists:map(fun(X) ->2*X end, L).

     [2*X || X<-L].   -list comprehensions

‣    Tuples:
     Book1 = {{isbn,”1-9343560-0-X”},{title,”Programming Erlang”},{authors,{“Joe
     Armstrong”}},{pages,515},{publisher,”The Pragmatic Programmer”}}
     {_,{_,Book1_title},_,_,_}=Book1.

‣    Funs:
     Double = fun(X)->2*X end.
erlang language basics

    • Terms
‣    Atoms, represent the static constants; lowercase letters-and-numbers-and-@ or any
     characters within single-quotes
     Book1 = {{isbn,”1-9343560-0-X”},{title,”Programming Erlang”},{authors,{“Joe
     Armstrong”}},{pages,515},{publisher,”The Pragmatic Programmer”}}

‣    Numbers: integers - limited by available memory, and floats - 64-bit format
‣    Strings: list of integers, within double-quotes
‣    Binaries: efficient to store large quantity of data, in form of sequence of unsigned 8-
     bit integers; BIFs that can manipulate binaries; Bit syntax that can pattern match
     against binaries.
     <<0,1,...,255>>

‣    Term comparisons: number<atom<reference<fun<port<pid<tuple<list<binary
erlang language basics


    • Variables
‣    single assignment, immutable, name must start with uppercase letter
‣    X=X+1 does not work in Erlang
‣    scope is the lexical unit in which it is defined
erlang language basics


• Recursion
     ‣     looping
     ‣ tail recursion efficiency
     (a) sum(0) -> 0;
           sum(N) -> sum(N-1)+N.
     (b)   do_sum(0, Total) -> Total;
           do_sum(N, Total) -> do_sum(N-1, Total+N).
erlang language basics
• Case expressions
        case Expression of
            Pattern1 [when Guard1] -> Expr_seq1;
              Pattern2 [when Guard2] -> Expr_seq2;
              ...
        end


• If expressions
        if
            Guard1 -> Expr_seq1;
            Guard2 -> Expr_seq2;
              ...
        end


• Exceptions
        try {
          block
        } catch (exception) {
          block
        } catch (exception) {
          block
        } ...
        finally {
         block
        }
erlang language basics

    • OTP patterns
‣    library of solutions for common problems ~ similar to an App Server container in
     JEE
‣    it is part of Erlang standard download
‣    can be utilized by using -behaviour(pattern_name)
‣    common patterns:
     -behaviour(gen_server).

     -behaviour(gen_event).
     -behaviour(supervisor).

     -behaviour(application).
erlang language basics
    • Mnesia
‣    distributed dbms that comes incorporated in the standard Erlang download
‣    can store any type of Erlang data structures
‣    can be configured to have both memory and disk storage
‣    examples:
     -record(books,{id, book}).
     B=#books{id={“1-9343560-0-X”},
                  book = {{isbn, “1-9343560-0-X”},{title, “Programming Erlang”},
                  {authors,{“Joe Armstrong”}},{pages,515},{publisher, “The
                  Pragmatic Programmer”}}
                  }
erlang language basics

    • Jinterface
‣    Java simulation of Erlang
‣    a mapping implementation of Erlang language elements into Java
‣    java erlang-simulated nodes can talk to the erlang nodes using erlang protocol
speculations

• sequential and parallel programming - two
  dimensions equally important in our problem
  solving
• concurrency might no longer remain an attribute
  of special problems
• spiral of change might be introducing some new
  forces on the OO paradigm

Contenu connexe

En vedette

Erlang For Five Nines
Erlang For Five NinesErlang For Five Nines
Erlang For Five NinesBarcamp Cork
 
Distributed Erlang Systems In Operation
Distributed Erlang Systems In OperationDistributed Erlang Systems In Operation
Distributed Erlang Systems In OperationAndy Gross
 
東京Node学園#8 Let It Crash!?
東京Node学園#8 Let It Crash!?東京Node学園#8 Let It Crash!?
東京Node学園#8 Let It Crash!?koichik
 
Benchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbersBenchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbersJustin Dorfman
 
Comparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms SoftwareComparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms Softwarel xf
 
Concurrency in Elixir with OTP
Concurrency in Elixir with OTPConcurrency in Elixir with OTP
Concurrency in Elixir with OTPJustin Reese
 
CodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере Nitrogen
CodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере NitrogenCodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере Nitrogen
CodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере NitrogenCodeFest
 
C++ Actor Model - You’ve Got Mail ...
C++ Actor Model - You’ve Got Mail ...C++ Actor Model - You’ve Got Mail ...
C++ Actor Model - You’ve Got Mail ...Gianluca Padovani
 
Intro to Erlang
Intro to ErlangIntro to Erlang
Intro to ErlangKen Pratt
 
Let it crash! The Erlang Approach to Building Reliable Services
Let it crash! The Erlang Approach to Building Reliable ServicesLet it crash! The Erlang Approach to Building Reliable Services
Let it crash! The Erlang Approach to Building Reliable ServicesBrian Troutwine
 
1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTP1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTPJordi Llonch
 
Node.jsエンジニア Erlangに入門するの巻
Node.jsエンジニア Erlangに入門するの巻Node.jsエンジニア Erlangに入門するの巻
Node.jsエンジニア Erlangに入門するの巻Recruit Technologies
 
Intro To Erlang
Intro To ErlangIntro To Erlang
Intro To Erlangasceth
 
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜 リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜 Yugo Shimizu
 
Imprementation of realtime_networkgame
Imprementation of realtime_networkgameImprementation of realtime_networkgame
Imprementation of realtime_networkgameSatoshi Yamafuji
 

En vedette (20)

Erlang For Five Nines
Erlang For Five NinesErlang For Five Nines
Erlang For Five Nines
 
git internals
git internalsgit internals
git internals
 
Erlang and Scalability
Erlang and ScalabilityErlang and Scalability
Erlang and Scalability
 
Distributed Erlang Systems In Operation
Distributed Erlang Systems In OperationDistributed Erlang Systems In Operation
Distributed Erlang Systems In Operation
 
東京Node学園#8 Let It Crash!?
東京Node学園#8 Let It Crash!?東京Node学園#8 Let It Crash!?
東京Node学園#8 Let It Crash!?
 
Benchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbersBenchmarks, performance, scalability, and capacity what's behind the numbers
Benchmarks, performance, scalability, and capacity what's behind the numbers
 
Comparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms SoftwareComparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms Software
 
Concurrency in Elixir with OTP
Concurrency in Elixir with OTPConcurrency in Elixir with OTP
Concurrency in Elixir with OTP
 
Erlang&rails
Erlang&railsErlang&rails
Erlang&rails
 
CodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере Nitrogen
CodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере NitrogenCodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере Nitrogen
CodeFest 2012. Трескин М. — Разработка Web-приложений на Comet-сервере Nitrogen
 
C++ Actor Model - You’ve Got Mail ...
C++ Actor Model - You’ve Got Mail ...C++ Actor Model - You’ve Got Mail ...
C++ Actor Model - You’ve Got Mail ...
 
Http streaming
Http streamingHttp streaming
Http streaming
 
Intro to Erlang
Intro to ErlangIntro to Erlang
Intro to Erlang
 
Let it crash! The Erlang Approach to Building Reliable Services
Let it crash! The Erlang Approach to Building Reliable ServicesLet it crash! The Erlang Approach to Building Reliable Services
Let it crash! The Erlang Approach to Building Reliable Services
 
1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTP1 hour dive into Erlang/OTP
1 hour dive into Erlang/OTP
 
Node.jsエンジニア Erlangに入門するの巻
Node.jsエンジニア Erlangに入門するの巻Node.jsエンジニア Erlangに入門するの巻
Node.jsエンジニア Erlangに入門するの巻
 
Erlang OTP
Erlang OTPErlang OTP
Erlang OTP
 
Intro To Erlang
Intro To ErlangIntro To Erlang
Intro To Erlang
 
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜 リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
 
Imprementation of realtime_networkgame
Imprementation of realtime_networkgameImprementation of realtime_networkgame
Imprementation of realtime_networkgame
 

Erlang vs. Java

  • 1. Erlang vs. Java January 19, 2011 Artan Cami
  • 2. (i) Erlang history (ii) Erlang resources (iii) Java history (iv) Compare philosophies (v) Problem definition (vi) JEE approach & principles (vii) JEE solution details (viii) Erlang/OTP approach & principles (ix) Erlang solution details (x) Erlang language basics (xi) Speculations
  • 3. erlang history http://www.erlang.org/course/history.html 1982-1985 telecom experiments with about 20 languages => need high symbolic language 1985-1986 experiments with Lisp, Prolog, Parlog... => need concurrency primitives and error recovery => need new language 1987 first experiments with Erlang 1988 “Erlang escapes from the lab!” 1990 Erlang presented in ISS’90 => new users introduced 1992 Erlang ported to VxWorks, PC, Mac ... 1993 Distribution is added to Erlang => run homogeneous Erlang to heterogeneous hardware 1997 OTP (open telecom platform) started 1998 Erlang banned => open source Erlang 2002 Concurrency Oriented Programming 2006 SMP (symmetric multiprocessing machine) Erlang - Multicore.
  • 4. erlang resources ๏ Programming Erlang: Software for a Concurrent World - Joe Armstrong - Jul 2007 ๏ ERLANG Programming - Francesco Cesarini, Simon Thompson - Jun 2009 ๏ Erlang and OTP in Action - Martin Logan, Eric Merritt, Richard Carlson - Nov 2010 ๏ www.erlang.org - Erlang Programming Language, Official Site ๏ www.trapexit.org - Erlang Community Site ๏ erlyweb.org - The Erlang Twist on Web Frameworks ๏ erlide.sourceforge.net - The Erlang IDE. Powered by Eclipse. ๏ www.infoq.com/interviews - interviews taken in Erlang Factory events.
  • 5. java history http://www.java.com/en/javahistory 1991 The Green Project begins 1992 “Oak” 1994 WebRunner - first browser for moving objects and executable content 1995 Oak becomes Java. Java technology released to a select group on wicked.neato.org 1996 JDKtm 1.0 released; first JavaOne conference 1997 Over 220,000 downloads of JDK 1.1 in just three weeks; JavaOne worlds largest developer conference with over 8,000 attendees 1998 JDK 1.1 2 million downloads; Visa Java Smart Card; JCP formalized 1999 J2EE beta released; Java 2 source code released; over 20,000 people in JavaOne 2001 Over 2 million downloads of J2EE 2003 About 75% of professional developers use Java as their primary language 2004 Mars-Rover touches down on Mars; J2SE 5 (Tiger) released 2005 4.5 million java developers; 2.5 billion Java-enabled devices
  • 6. philosophies/principles • Java : • “the computer is the network” • write once, run anywhere • simple • concurrency multithreading • object orientated programming • Erlang : • the world is parallel • concurrent processes belong to the language - not OS • very light weight concurrency • share nothing; no mutable state; no locks • pure asynchronous message passing • “let it crash” - no defensive programming • functional programming
  • 7. bookstore problem typical online bookstore - books: find books, display list of books, display the book details • book details: book summary information, editorial reviews, product details, authors details, customer reviews, related books: frequently bought together, other books on this topic, other books by this author(s) - customer: create and maintain profile; store, find, and display transaction history. - orders: shopping cart capability; payment and shipment types; order placement. - non-functional requirements ➡ S - store app, B - books apps, C - customer apps; O - order apps
  • 8. jee approach and patterns • MVC • Define layers: presentation, model, and data • Model: EJB3 - stateless, stateful, singleton session beans; message-driven beans; • container management, session facade, entity access object; • ORM layer: JPA implementation • EntityManager, entity POJOs; • Pick a presentation framework: struts, jsf, templating, or portal
  • 9. jee - deployment strategy collocated JVM 1 Applications S B C O JVM 2 Applications Load Balancer S B C O JVM 3 Applications S B C O
  • 10. jee - deployment strategy distributed JVM 2 EJB Applications BEJB JVM 1 Web Applications JVM 3 SWEB BWEB CWEB OWEB EJB Applications CEJB OEJB
  • 11. jee - books applications J V M 1 J V M 2 W e b C o n t a i n e r E J B C o n t a i n e r ORM BookEntity BookEAO EJB RelatedBooksEntity BooksController Books EJB BookContentEntity AuthorEntity BooksView RelatedBookslEAO EJB BookDetailView ...View PublisherEntity BookContentView
  • 12. jee -customer applications J V M 1 J V M 3 W e b C o n t a i n e r E J B C o n t a i n e r ORM ProfileEntity ProfileEAO EJB CustomerController PaymentTypesEntity Customer EJB OrdersHistoryEntity CustomerProfileView OrdersHistoryEAO ...View EJB OrdersHisotryView
  • 13. jee - orders applications J V M 1 J V M 3 W e b C o n t a i n e r E J B C o n t a i n e r ORM ShoppingCartContr ShoppingCartEAO ShoppingCartEntity ShoppingCart EJB EJB OrdersController PaymentEntity PaymentsEAO ShippingEntity EJB ShoppingCartView Orders EJB ...View PaymentView OrdersEntity OrdersEAO EJB
  • 14. jee - sequence diagram display book details BooksController BooksEJB BooksEAO RelatedBooksEAO 1 2 3 4 5 7 BookView 6 BookDetailView 8 9 RelatedBooksView 10 11 12 13 14
  • 15. erlang/otp approach and patterns • Use large number of processes in order to distribute/ parallelize as much as possible; • process is the main building block with its own stack, garbage collection, message queue, security model. • message sending/receiving simplicity made possible by pattern matching and simple data structures; • Avoid side effects - no shared resources among processes; • variables that don’t vary - single assignment. No mutable state, no shared memory, no locks; • Small messages, big computations • Distributed database Mnesia • OTP patterns: • gen_server, event_handler, supervisor, application, ...
  • 16. erlang - sequence & concurrency diagram display book details BooksController BooksDetailModel 1 BooksDetailController 2 3 BookDetailView 4 5 6 7 RelatedBooksModel RelatedBooksController 2’ 3’ RelatedBooksView 4’ 5’ 6’ 7’ 8
  • 17. erlang - books applications Node 2 BooksDetails BooksDetails Model Model Node 1 BooksDetails RelatedBooks RelatedBooks Controller Controller View BooksDetail View Books Controller
  • 18. erlang - deployment strategy Distributed Node 2 Node 3 B O C processes processes processes Node 1 OWEB BWEB processes CWEB processes processes SWEB processes
  • 19. erlang language basics • Modules: .erl files ~ similar to .java files ‣ .beam is the compiled module extension ~ similar to .class in java ‣ -module(module_name). ~ similar to public class in java ‣ -export([list of public functions]). ~ similar to public method modifier in java ‣ -import(module,[list of public functions]). ~ similar to import in java ‣ other module attributes: -behaviour(otp behavior pattern name). -record(record_name, tuple). -compile(options).
  • 20. erlang language basics • Functions ~ similar to methods in java ‣ function_name( arguments ) -> function body. ‣ function body consists of instructions separated by commas ‣ one of the instructions results to the function output ‣ BIFs - build in functions ‣ function is called as module_name:function_name(arguments)
  • 21. erlang language basics • Processes ‣ the building blocks of concurrency ‣ simple to create; erlang:system_info(process_limit) 32,767 ‣ simple primitives: spawn, send, receive: Pid = spawn(Node,Fun). Pid ! Message. receive ... end. ‣ Links, Exit signals, System processes spawn_link(Node,Fun) -> Pid process_flag(trap_exit,true). exit(Pid, Why)->true. erlang:monitor(process,Item)->MonitorRef ‣ Registered processes ‣ Independent stack, message queue, garbage collection
  • 22. erlang language basics • Messages ‣ asynchronous ‣ pass by copying ‣ lightweight and simple due to simple data structures ‣ selective receive due to pattern matching: loop(Name,Mod,OldState)-> receive {From,{swap_code,NewMod}}-> From!{Name,acknowledged}, loop(Name,NewMod,OldState); {From,Request}-> {Response,NewState}=Mod:handle(Request,OldState), From!{Name,Response}, loop(Name,Mod,NewState) end.
  • 23. erlang language basics • Terms ‣ Lists: Books = [Book1,Book2,Book3] Books = [Book1 | RestOfBooks] Book1 = {{isbn,”1-9343560-0-X”},{title,”Programming Erlang”},{authors,{“Joe Armstrong”}},{pages,515},{publisher,”The Pragmatic Programmer”}} Book2 = {{isbn,”9781933988788”},{title,”Erlang and OTP in Action”}, {authors,{“Martin Logan”,”Eric Merritt”,”Richard Carlson”}},{pages,397}, {publisher,”Manning”}} lists:map(fun(X) ->2*X end, L). [2*X || X<-L]. -list comprehensions ‣ Tuples: Book1 = {{isbn,”1-9343560-0-X”},{title,”Programming Erlang”},{authors,{“Joe Armstrong”}},{pages,515},{publisher,”The Pragmatic Programmer”}} {_,{_,Book1_title},_,_,_}=Book1. ‣ Funs: Double = fun(X)->2*X end.
  • 24. erlang language basics • Terms ‣ Atoms, represent the static constants; lowercase letters-and-numbers-and-@ or any characters within single-quotes Book1 = {{isbn,”1-9343560-0-X”},{title,”Programming Erlang”},{authors,{“Joe Armstrong”}},{pages,515},{publisher,”The Pragmatic Programmer”}} ‣ Numbers: integers - limited by available memory, and floats - 64-bit format ‣ Strings: list of integers, within double-quotes ‣ Binaries: efficient to store large quantity of data, in form of sequence of unsigned 8- bit integers; BIFs that can manipulate binaries; Bit syntax that can pattern match against binaries. <<0,1,...,255>> ‣ Term comparisons: number<atom<reference<fun<port<pid<tuple<list<binary
  • 25. erlang language basics • Variables ‣ single assignment, immutable, name must start with uppercase letter ‣ X=X+1 does not work in Erlang ‣ scope is the lexical unit in which it is defined
  • 26. erlang language basics • Recursion ‣ looping ‣ tail recursion efficiency (a) sum(0) -> 0; sum(N) -> sum(N-1)+N. (b) do_sum(0, Total) -> Total; do_sum(N, Total) -> do_sum(N-1, Total+N).
  • 27. erlang language basics • Case expressions case Expression of Pattern1 [when Guard1] -> Expr_seq1; Pattern2 [when Guard2] -> Expr_seq2; ... end • If expressions if Guard1 -> Expr_seq1; Guard2 -> Expr_seq2; ... end • Exceptions try { block } catch (exception) { block } catch (exception) { block } ... finally { block }
  • 28. erlang language basics • OTP patterns ‣ library of solutions for common problems ~ similar to an App Server container in JEE ‣ it is part of Erlang standard download ‣ can be utilized by using -behaviour(pattern_name) ‣ common patterns: -behaviour(gen_server). -behaviour(gen_event). -behaviour(supervisor). -behaviour(application).
  • 29. erlang language basics • Mnesia ‣ distributed dbms that comes incorporated in the standard Erlang download ‣ can store any type of Erlang data structures ‣ can be configured to have both memory and disk storage ‣ examples: -record(books,{id, book}). B=#books{id={“1-9343560-0-X”}, book = {{isbn, “1-9343560-0-X”},{title, “Programming Erlang”}, {authors,{“Joe Armstrong”}},{pages,515},{publisher, “The Pragmatic Programmer”}} }
  • 30. erlang language basics • Jinterface ‣ Java simulation of Erlang ‣ a mapping implementation of Erlang language elements into Java ‣ java erlang-simulated nodes can talk to the erlang nodes using erlang protocol
  • 31. speculations • sequential and parallel programming - two dimensions equally important in our problem solving • concurrency might no longer remain an attribute of special problems • spiral of change might be introducing some new forces on the OO paradigm

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n