SlideShare a Scribd company logo
1 of 40
Download to read offline
Intro
Making things work
           Verdict




The Proactor Pattern

          Ant´nio Sousa
             o

                      UU


 30 de Setembro de 2005




     Ant´nio Sousa
        o                  The Proactor Pattern
Intro
                                              Proactor?
                        Making things work
                                              In detail...
                                   Verdict


Outline


      Intro
  1
         Proactor?
         In detail...

      Making things work
  2
       JAVA!
       Some code

      Verdict
  3
        Consequences
        Finale



                             Ant´nio Sousa
                                o             The Proactor Pattern
Intro
                                             Proactor?
                       Making things work
                                             In detail...
                                  Verdict


Dictionary definition




  proactive
  adjective
  (of a person, policy or action) creating or controlling a situation by
  causing something to happen rather than responding to it after it
  has happened: be proactive in identifying and preventing potential
  problems




                            Ant´nio Sousa
                               o             The Proactor Pattern
Intro
                                            Proactor?
                      Making things work
                                            In detail...
                                 Verdict


My definition




  proactor
  pattern
  allows an efficient use of the asynchronous mechanisms provided
  by operating systems in event-driven applications, by integrating
  the demultiplexing of completion events and the dispatching of
  their event handlers;




                           Ant´nio Sousa
                              o             The Proactor Pattern
Intro
                                             Proactor?
                       Making things work
                                             In detail...
                                  Verdict


A little background


      Asynchronous I/O
          Operations run in the background and do not block user
          applications (libaio, linux kernel 2.6, Windows NT)
      Completion events
          When an asynchronous I/O operation finishes a completion
          event is generated saying that the operation is completed (or
          not)
      Event handlers
          The application-specific component that processes the results
          of the asynchronous operations




                            Ant´nio Sousa
                               o             The Proactor Pattern
Intro
                                            Proactor?
                      Making things work
                                            In detail...
                                 Verdict


Why do we need this?



  In multithreaded or reactive concurrency designs we have:
      Synchronization complexity
      Performance overhead (context switching)
      Complex programming

  Proactor Pattern!
  Performance in concurrency without its liabilities




                           Ant´nio Sousa
                              o             The Proactor Pattern
Intro
                                           Proactor?
                     Making things work
                                           In detail...
                                Verdict


Participants


  Asynchronous operations
  Potentially long-duration operations implementing some kind of
  service (invoked on a handle) that executes without blocking

  Completion handlers
  Interface defining the hook methods for processing the completion
  events generated by asynchronous operations

  Asynchronous operation processor
  Executes the asynchronous operations to completion generating
  and queuing the corresponding completion events


                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                           Proactor?
                     Making things work
                                           In detail...
                                Verdict


Participants

  Completion event queue
  Buffer where the asynchronous operation processor queues the
  completion events associated with a specific handle

  Completion Dispatcher (Proactor)
  Makes use of the asynchronous event demultiplexer to dequeue
  completion event and then dispatches them to the correspondent
  hook method of the completion handler

  Initiator
  Any entity in the application that invokes an asynchronous
  operation


                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                       Proactor?
                 Making things work
                                       In detail...
                            Verdict


Collaborations




                      Ant´nio Sousa
                         o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                         Proactor?
                   Making things work
                                         In detail...
                              Verdict


A little analogy




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                              JAVA!
                        Making things work
                                              Some code
                                   Verdict


java.nio.*

  Features
  The NIO APIs include the following features:
       Buffers for data of primitive types
       Character-set encoders and decoders
       A pattern-matching facility based on Perl-style regular
       expressions
       Channels, a new primitive I/O abstraction
       A file interface that supports locks and memory mapping
       A multiplexed, non-blocking I/O facility for writing scalable
       servers
  source: http://java.sun.com/j2se/1.4.2/docs/guide/nio/


                             Ant´nio Sousa
                                o             The Proactor Pattern
Intro
                                              JAVA!
                        Making things work
                                              Some code
                                   Verdict


java.nio.*

  Features
  The NIO APIs include the following features:
       Buffers for data of primitive types
       Character-set encoders and decoders
       A pattern-matching facility based on Perl-style regular
       expressions
       Channels, a new primitive I/O abstraction
       A file interface that supports locks and memory mapping
       A multiplexed, non-blocking I/O facility for writing scalable
       servers
  source: http://java.sun.com/j2se/1.4.2/docs/guide/nio/


                             Ant´nio Sousa
                                o             The Proactor Pattern
Intro
                                            JAVA!
                      Making things work
                                            Some code
                                 Verdict


This sounds interesting!

  java.nio.channels
  Defines channels, which represent connections to entities that are
  capable of performing I/O operations, such as files and sockets;
  defines selectors, for multiplexed, non-blocking I/O operations.


   SocketChannel              Selector                             SelectionKey
   A selectable               A multiplexor of                     A token
   channel for                SelectableChan-                      representing the
   stream-oriented            nel                                  registration of a
   connecting                 objects.                             SelectableChan-
   sockets.                                                        nel with a
                                                                   Selector.

                           Ant´nio Sousa
                              o             The Proactor Pattern
Intro
                                            JAVA!
                      Making things work
                                            Some code
                                 Verdict


Completion handler

      Type for the results
  SelectionKey
  Allows: defining operation type; obtaining the selector and the
  channel associated; include any Object as an attachment

      Type of dispatching (objects/function pointers)
      Dispatch strategy (single/multimethod)

  CompletionHandler.java
  public interface CompletionHandler {
    public void handleEvent(SelectionKey sk);
  }



                           Ant´nio Sousa
                              o             The Proactor Pattern
Intro
                                         JAVA!
                   Making things work
                                         Some code
                              Verdict


Asynchronous operation processor




     Asynchronous operation interface (Wrapper facade/ACT)
     Asynchronous operation processor mechanism




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                            JAVA!
                      Making things work
                                            Some code
                                 Verdict


Proactor



      Hierarchy (multi-plattform proactors)
      Completion event queue and demultiplexing mechanisms
  Selector
  Queue: key set, selected-key set, cancelled-key set
  Demultiplexing: select() method

      Dispatch strategy
      Concrete implementation




                           Ant´nio Sousa
                              o             The Proactor Pattern
Intro
                                           JAVA!
                     Making things work
                                           Some code
                                Verdict


Proactor


  Proactor.java
  public class Proactor {
    private Selector selector;

    public Proactor() {
      selector =
        SelectorProvider.provider().openSelector();
    }

    public void register(SelectableChannel handle,
               int eventType, Object completionHandler) {
      handle.register(selector, eventType, completionHandler);
    }
    (...)



                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                             JAVA!
                       Making things work
                                             Some code
                                  Verdict


Proactor


  Proactor.java
      (...)
      public void handleEvent() {
        while (selector.select() > 0) {
          Set readyKeys = selector.selectedKeys();
          Iterator i = readyKeys.iterator();
          while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            i.remove();
            (CompletionHandler) sk.attachment()).handleEvent(sk);
          }
        }
      }
  }



                            Ant´nio Sousa
                               o             The Proactor Pattern
Intro
                                           JAVA!
                     Making things work
                                           Some code
                                Verdict


Concrete completion handlers


      State
      Handles
      Implementation

  Acceptor.java
  public class Acceptor implements CompletionHandler{
    private SocketAddress address;
    private ServerSocketChannel ssc;
    private Proactor proactor;
    (...)




                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                          JAVA!
                    Making things work
                                          Some code
                               Verdict


Concrete completion handlers


  Acceptor.java
   (...)
   public Acceptor(Proactor p, String host, int port) {
     address = new InetSocketAddress(host, port);
     proactor = p;
   }

   public void accept() {
     ssc = ServerSocketChannel.open();
     ssc.configureBlocking(false);
     ssc.socket().bind(this.address);
     proactor.register(ssc, SelectionKey.OP_ACCEPT, this);
   }
   (...)



                         Ant´nio Sousa
                            o             The Proactor Pattern
Intro
                                             JAVA!
                       Making things work
                                             Some code
                                  Verdict


Concrete completion handlers


  Acceptor.java
      (...)
      public void handleEvent(SelectionKey sk) {
        ServerSocketChannel handle =
          (ServerSocketChannel) sk.channel();
        SocketChannel s = null;
        s = handle.accept();
        s.configureBlocking(false);
        Worker w = new Worker(proactor, s);
        w.work();
      }
  }




                            Ant´nio Sousa
                               o             The Proactor Pattern
Intro
                                           JAVA!
                     Making things work
                                           Some code
                                Verdict


Concrete completion handlers


  Worker.java
  public class Worker implements CompletionHandler {
    private Proactor proactor;
    private SocketChannel socket;
    private ByteBuffer b_read;
    private ByteBuffer b_write;

    public Worker(Proactor p, SocketChannel s) {
      proactor = p;
      socket = s;
      b_read = ByteBuffer.allocateDirect(1024);
    }
    (...)




                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                             JAVA!
                       Making things work
                                             Some code
                                  Verdict


Concrete completion handlers


  Worker.java
      (...)
      public void work() {
        socket.read(b_read);
        proactor.register(socket, SelectionKey.OP_READ, this);
  }

      public void handleEvent(SelectionKey sk) {
        System.out.println(new String(b_read.array()));
      }
  }




                            Ant´nio Sousa
                               o             The Proactor Pattern
Intro
                                           JAVA!
                     Making things work
                                           Some code
                                Verdict


Server



  Server.java
  public class Server {
    public static void main(String args[]) {
      Proactor proactor = new Proactor();
      Acceptor acceptor =
        new Acceptor(proactor, quot;localhostquot;, 9999);
      acceptor.accept();
      proactor.handleEvent();
    }
  }




                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                          Consequences
                    Making things work
                                          Finale
                               Verdict


Benefits




     Separation of concerns
     Portability
     Different concurrency mechanisms
     Simplification of application synchronization




                         Ant´nio Sousa
                            o             The Proactor Pattern
Intro
                                         Consequences
                   Making things work
                                         Finale
                              Verdict


Drawbacks




     Efficiency depends on the platform
     Complexity of programming, debugging and testing
     Scheduling and controlling asynchronous operations




                        Ant´nio Sousa
                           o             The Proactor Pattern
Intro
                                            Consequences
                      Making things work
                                            Finale
                                 Verdict


Variants
  Asynchronous Completion Handlers
  All completion handlers are required to act as initiators

  Concurrent Asynchronous Event Demultiplexer
  The proactor demultiplexes and dispatches completion handlers
  concurrently

  Shared Completion Handlers
  Initiators can invoke multiple asynchronous operations at the same
  time sharing the same completion handler

  Asynchronous Operation Processor Emulation
  When asynchronous operations are not available in the OS, it’s
  possible to emulate them (thread per operation,thread pool)
                           Ant´nio Sousa
                              o             The Proactor Pattern
Intro
                                           Consequences
                     Making things work
                                           Finale
                                Verdict


Known uses

  Completion ports in Windows NT
  Windows NT acts as an asynchronous operation processor:
  supports various types of asynchronous operations; generates
  completion events and queues them in completion ports

  POSIX AIO
  aio*() family APIs; similar to Windows NT

  ACE Proactor Framework
  ACE provides a portable Proactor framework (AceProactor)

  Device driver interrupt-handling mechanisms
  Hardware devices driven by asynchronous interrupts

                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                           Consequences
                     Making things work
                                           Finale
                                Verdict


Related patterns

  Asynchronous completion token
  Usually used in conjunction with the Proactor pattern. For every
  asynch op invoked, an ACT is created and returned to the caller
  when the operation finishes

  Observer
  All dependents are updated automatically when a change occurs;
  in the Proactor handlers are informed automatically when events
  occur

  Reactor
  Considered an asynchronous version of the Reactor Pattern


                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                           Consequences
                     Making things work
                                           Finale
                                Verdict


Related patterns

  Active Object
  Decouples method execution from invocation; in Proactor Pattern
  the asynchronous processor performs operation on behalf of the
  initiators

  Chain of Responsability
  Decouples event handlers from event sources; initiators and
  completion handlers in Proactor (although in CoR the source has
  no knowledge about which handler will be executed)

  Leader/Followers and Half-Sync/Half-Async
  Demultiplex and process various types of events synchronously


                          Ant´nio Sousa
                             o             The Proactor Pattern
Intro
                                       Consequences
             Making things work
                                       Finale
                        Verdict


Questions?




                                   ?




                  Ant´nio Sousa
                     o                 The Proactor Pattern
Intro
                                            Consequences
                      Making things work
                                            Finale
                                 Verdict


Question




  Considerer the following Proactor design decisions:
      Multiple-proactor implementation
      Spawned thread per event
  Describe the different uses, advantages and disadvantages of both
  decisions




                           Ant´nio Sousa
                              o             The Proactor Pattern

More Related Content

More from l xf

Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Evel xf
 
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
 
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...l xf
 
Messaging With Erlang And Jabber
Messaging With  Erlang And  JabberMessaging With  Erlang And  Jabber
Messaging With Erlang And Jabberl xf
 
Improving Robustness In Distributed Systems
Improving Robustness In Distributed SystemsImproving Robustness In Distributed Systems
Improving Robustness In Distributed Systemsl xf
 
Concurrency And Erlang
Concurrency And ErlangConcurrency And Erlang
Concurrency And Erlangl xf
 
Learning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential UsersLearning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential Usersl xf
 
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...l xf
 

More from l xf (8)

Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
 
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
 
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...
 
Messaging With Erlang And Jabber
Messaging With  Erlang And  JabberMessaging With  Erlang And  Jabber
Messaging With Erlang And Jabber
 
Improving Robustness In Distributed Systems
Improving Robustness In Distributed SystemsImproving Robustness In Distributed Systems
Improving Robustness In Distributed Systems
 
Concurrency And Erlang
Concurrency And ErlangConcurrency And Erlang
Concurrency And Erlang
 
Learning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential UsersLearning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential Users
 
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
 

Recently uploaded

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
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Recently uploaded (20)

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
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

The Proactor Pattern

  • 1. Intro Making things work Verdict The Proactor Pattern Ant´nio Sousa o UU 30 de Setembro de 2005 Ant´nio Sousa o The Proactor Pattern
  • 2. Intro Proactor? Making things work In detail... Verdict Outline Intro 1 Proactor? In detail... Making things work 2 JAVA! Some code Verdict 3 Consequences Finale Ant´nio Sousa o The Proactor Pattern
  • 3. Intro Proactor? Making things work In detail... Verdict Dictionary definition proactive adjective (of a person, policy or action) creating or controlling a situation by causing something to happen rather than responding to it after it has happened: be proactive in identifying and preventing potential problems Ant´nio Sousa o The Proactor Pattern
  • 4. Intro Proactor? Making things work In detail... Verdict My definition proactor pattern allows an efficient use of the asynchronous mechanisms provided by operating systems in event-driven applications, by integrating the demultiplexing of completion events and the dispatching of their event handlers; Ant´nio Sousa o The Proactor Pattern
  • 5. Intro Proactor? Making things work In detail... Verdict A little background Asynchronous I/O Operations run in the background and do not block user applications (libaio, linux kernel 2.6, Windows NT) Completion events When an asynchronous I/O operation finishes a completion event is generated saying that the operation is completed (or not) Event handlers The application-specific component that processes the results of the asynchronous operations Ant´nio Sousa o The Proactor Pattern
  • 6. Intro Proactor? Making things work In detail... Verdict Why do we need this? In multithreaded or reactive concurrency designs we have: Synchronization complexity Performance overhead (context switching) Complex programming Proactor Pattern! Performance in concurrency without its liabilities Ant´nio Sousa o The Proactor Pattern
  • 7. Intro Proactor? Making things work In detail... Verdict Participants Asynchronous operations Potentially long-duration operations implementing some kind of service (invoked on a handle) that executes without blocking Completion handlers Interface defining the hook methods for processing the completion events generated by asynchronous operations Asynchronous operation processor Executes the asynchronous operations to completion generating and queuing the corresponding completion events Ant´nio Sousa o The Proactor Pattern
  • 8. Intro Proactor? Making things work In detail... Verdict Participants Completion event queue Buffer where the asynchronous operation processor queues the completion events associated with a specific handle Completion Dispatcher (Proactor) Makes use of the asynchronous event demultiplexer to dequeue completion event and then dispatches them to the correspondent hook method of the completion handler Initiator Any entity in the application that invokes an asynchronous operation Ant´nio Sousa o The Proactor Pattern
  • 9. Intro Proactor? Making things work In detail... Verdict Collaborations Ant´nio Sousa o The Proactor Pattern
  • 10. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 11. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 12. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 13. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 14. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 15. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 16. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 17. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 18. Intro Proactor? Making things work In detail... Verdict A little analogy Ant´nio Sousa o The Proactor Pattern
  • 19. Intro JAVA! Making things work Some code Verdict java.nio.* Features The NIO APIs include the following features: Buffers for data of primitive types Character-set encoders and decoders A pattern-matching facility based on Perl-style regular expressions Channels, a new primitive I/O abstraction A file interface that supports locks and memory mapping A multiplexed, non-blocking I/O facility for writing scalable servers source: http://java.sun.com/j2se/1.4.2/docs/guide/nio/ Ant´nio Sousa o The Proactor Pattern
  • 20. Intro JAVA! Making things work Some code Verdict java.nio.* Features The NIO APIs include the following features: Buffers for data of primitive types Character-set encoders and decoders A pattern-matching facility based on Perl-style regular expressions Channels, a new primitive I/O abstraction A file interface that supports locks and memory mapping A multiplexed, non-blocking I/O facility for writing scalable servers source: http://java.sun.com/j2se/1.4.2/docs/guide/nio/ Ant´nio Sousa o The Proactor Pattern
  • 21. Intro JAVA! Making things work Some code Verdict This sounds interesting! java.nio.channels Defines channels, which represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations. SocketChannel Selector SelectionKey A selectable A multiplexor of A token channel for SelectableChan- representing the stream-oriented nel registration of a connecting objects. SelectableChan- sockets. nel with a Selector. Ant´nio Sousa o The Proactor Pattern
  • 22. Intro JAVA! Making things work Some code Verdict Completion handler Type for the results SelectionKey Allows: defining operation type; obtaining the selector and the channel associated; include any Object as an attachment Type of dispatching (objects/function pointers) Dispatch strategy (single/multimethod) CompletionHandler.java public interface CompletionHandler { public void handleEvent(SelectionKey sk); } Ant´nio Sousa o The Proactor Pattern
  • 23. Intro JAVA! Making things work Some code Verdict Asynchronous operation processor Asynchronous operation interface (Wrapper facade/ACT) Asynchronous operation processor mechanism Ant´nio Sousa o The Proactor Pattern
  • 24. Intro JAVA! Making things work Some code Verdict Proactor Hierarchy (multi-plattform proactors) Completion event queue and demultiplexing mechanisms Selector Queue: key set, selected-key set, cancelled-key set Demultiplexing: select() method Dispatch strategy Concrete implementation Ant´nio Sousa o The Proactor Pattern
  • 25. Intro JAVA! Making things work Some code Verdict Proactor Proactor.java public class Proactor { private Selector selector; public Proactor() { selector = SelectorProvider.provider().openSelector(); } public void register(SelectableChannel handle, int eventType, Object completionHandler) { handle.register(selector, eventType, completionHandler); } (...) Ant´nio Sousa o The Proactor Pattern
  • 26. Intro JAVA! Making things work Some code Verdict Proactor Proactor.java (...) public void handleEvent() { while (selector.select() > 0) { Set readyKeys = selector.selectedKeys(); Iterator i = readyKeys.iterator(); while (i.hasNext()) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); (CompletionHandler) sk.attachment()).handleEvent(sk); } } } } Ant´nio Sousa o The Proactor Pattern
  • 27. Intro JAVA! Making things work Some code Verdict Concrete completion handlers State Handles Implementation Acceptor.java public class Acceptor implements CompletionHandler{ private SocketAddress address; private ServerSocketChannel ssc; private Proactor proactor; (...) Ant´nio Sousa o The Proactor Pattern
  • 28. Intro JAVA! Making things work Some code Verdict Concrete completion handlers Acceptor.java (...) public Acceptor(Proactor p, String host, int port) { address = new InetSocketAddress(host, port); proactor = p; } public void accept() { ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ssc.socket().bind(this.address); proactor.register(ssc, SelectionKey.OP_ACCEPT, this); } (...) Ant´nio Sousa o The Proactor Pattern
  • 29. Intro JAVA! Making things work Some code Verdict Concrete completion handlers Acceptor.java (...) public void handleEvent(SelectionKey sk) { ServerSocketChannel handle = (ServerSocketChannel) sk.channel(); SocketChannel s = null; s = handle.accept(); s.configureBlocking(false); Worker w = new Worker(proactor, s); w.work(); } } Ant´nio Sousa o The Proactor Pattern
  • 30. Intro JAVA! Making things work Some code Verdict Concrete completion handlers Worker.java public class Worker implements CompletionHandler { private Proactor proactor; private SocketChannel socket; private ByteBuffer b_read; private ByteBuffer b_write; public Worker(Proactor p, SocketChannel s) { proactor = p; socket = s; b_read = ByteBuffer.allocateDirect(1024); } (...) Ant´nio Sousa o The Proactor Pattern
  • 31. Intro JAVA! Making things work Some code Verdict Concrete completion handlers Worker.java (...) public void work() { socket.read(b_read); proactor.register(socket, SelectionKey.OP_READ, this); } public void handleEvent(SelectionKey sk) { System.out.println(new String(b_read.array())); } } Ant´nio Sousa o The Proactor Pattern
  • 32. Intro JAVA! Making things work Some code Verdict Server Server.java public class Server { public static void main(String args[]) { Proactor proactor = new Proactor(); Acceptor acceptor = new Acceptor(proactor, quot;localhostquot;, 9999); acceptor.accept(); proactor.handleEvent(); } } Ant´nio Sousa o The Proactor Pattern
  • 33. Intro Consequences Making things work Finale Verdict Benefits Separation of concerns Portability Different concurrency mechanisms Simplification of application synchronization Ant´nio Sousa o The Proactor Pattern
  • 34. Intro Consequences Making things work Finale Verdict Drawbacks Efficiency depends on the platform Complexity of programming, debugging and testing Scheduling and controlling asynchronous operations Ant´nio Sousa o The Proactor Pattern
  • 35. Intro Consequences Making things work Finale Verdict Variants Asynchronous Completion Handlers All completion handlers are required to act as initiators Concurrent Asynchronous Event Demultiplexer The proactor demultiplexes and dispatches completion handlers concurrently Shared Completion Handlers Initiators can invoke multiple asynchronous operations at the same time sharing the same completion handler Asynchronous Operation Processor Emulation When asynchronous operations are not available in the OS, it’s possible to emulate them (thread per operation,thread pool) Ant´nio Sousa o The Proactor Pattern
  • 36. Intro Consequences Making things work Finale Verdict Known uses Completion ports in Windows NT Windows NT acts as an asynchronous operation processor: supports various types of asynchronous operations; generates completion events and queues them in completion ports POSIX AIO aio*() family APIs; similar to Windows NT ACE Proactor Framework ACE provides a portable Proactor framework (AceProactor) Device driver interrupt-handling mechanisms Hardware devices driven by asynchronous interrupts Ant´nio Sousa o The Proactor Pattern
  • 37. Intro Consequences Making things work Finale Verdict Related patterns Asynchronous completion token Usually used in conjunction with the Proactor pattern. For every asynch op invoked, an ACT is created and returned to the caller when the operation finishes Observer All dependents are updated automatically when a change occurs; in the Proactor handlers are informed automatically when events occur Reactor Considered an asynchronous version of the Reactor Pattern Ant´nio Sousa o The Proactor Pattern
  • 38. Intro Consequences Making things work Finale Verdict Related patterns Active Object Decouples method execution from invocation; in Proactor Pattern the asynchronous processor performs operation on behalf of the initiators Chain of Responsability Decouples event handlers from event sources; initiators and completion handlers in Proactor (although in CoR the source has no knowledge about which handler will be executed) Leader/Followers and Half-Sync/Half-Async Demultiplex and process various types of events synchronously Ant´nio Sousa o The Proactor Pattern
  • 39. Intro Consequences Making things work Finale Verdict Questions? ? Ant´nio Sousa o The Proactor Pattern
  • 40. Intro Consequences Making things work Finale Verdict Question Considerer the following Proactor design decisions: Multiple-proactor implementation Spawned thread per event Describe the different uses, advantages and disadvantages of both decisions Ant´nio Sousa o The Proactor Pattern