SlideShare a Scribd company logo
1 of 14
Download to read offline
LIGHTNING TALK
REPLACING THREADS WITH ACTORS FOR
CONCURRENT WEB APPLICATION SERVICE
CALLS
Martin Anderson
LJC Open Conference 2011
CONCURRENT SERVICE CALLS



 •  Most web pages need data from multiple
    sources
 •  Scatter/Gather approach to perform all the
    service calls in parallel then rendering the
    responses




 2
CONCURRENCY MODEL
                    dispatch service
                          calls




      rendering     controller’s job
     starts early        done


 3
THREADS



•  Well understood (if not always well
   implemented!)
•  java.util.concurrent library eases the pain
•  Resource usage?




 4
ACTORS



•    Been around since 1973
•    Erlang popularised usage
•    Actor library for Java? Akka!
•    Most strongly associated with Scala but
     has a Java API




 5
USING AN EXECUTOR SERVICE IN A SERVLET


 public void doGet(HttpServletRequest request, HttpServletResponse
 response) throws…{
     List<MyServiceCallable> myServiceCallables =
         new ArrayList<MyServiceCallable>();

         for (int ii = 0; ii < 10; ii++) {
             myServiceCallables.add(new MyServiceCallablle(remoteClient));
         }

         List<Future<String>> futures =
             executorService.invokeAll(myServiceCallables);
 …
         for (Future future : futures) {
             writer.write( future.get() );
         }
 …
 }

     6
USING AKKA ACTORS IN A SERVLET


 public void doGet(HttpServletRequest request, HttpServletResponse
 response) throws…{

         Works works = new Works();
         for (int ii = 0; ii < 10; ii++) {
             works.add(new Work()));
         }
         masterActor.tell(works);

         List<Future<String>> futures = works.getFutures();
 …
         for (Future future : futures) {
             writer.write( future.get() );
         }
 …
 }


     7
SO WHAT’S IN AN ACTOR 1?


 public class MasterActor extends UntypedActor {

      private ActorRef router;

      static class LoadBalancer extends UntypedLoadBalancer {
          private final InfiniteIterator<ActorRef> workers;

          public LoadBalancer(ActorRef[] workers) {
              this.workers =
                 new CyclicIterator<ActorRef>(asList(workers));
          }

          public InfiniteIterator<ActorRef> seq() {
              return workers;
          }
      }


  8
SO WHAT’S IN AN ACTOR 2?

  public MasterActor(final int numWorkers, final RemoteClient
 remoteClient) {
         // create an array of started workers
         final ActorRef[] workers = new ActorRef[numWorkers];
         for (int i = 0; i < numWorkers; i++) {
             workers[i] = actorOf(
                     new UntypedActorFactory() {
                         public UntypedActor create() {
                             return new WorkerActor(remoteClient);
                         }
                     })
                     .start();
         }
         // wrap all the workers with a load-balancing router
         router = actorOf(new UntypedActorFactory() {
             public UntypedActor create() {
                 return new LoadBalancer(workers);
             }
         }).start();
     }
  9
SO WHAT’S IN AN ACTOR 3?

      // message handler in MasterActor
      public void onReceive(Object message) {

          if (message instanceof Works) {
              for (Work work : ((Works) message).getAll()) {
                  router.tell(work);
              }
          }
      }




 10
SO WHAT’S IN AN ACTOR 4?

 public class WorkerActor extends UntypedActor {

      RemoteClient remoteClient;

      public WorkerActor(RemoteClient remoteClient) {
          this.remoteClient = remoteClient;
      }

      @Override
      public void onReceive(Object message) throws Exception {
          if (message instanceof Work) {
              Work work = (Work) message;
              remoteClient.execute(work);
          }
      }
 }




 11
SO WHAT’S IN OUR REMOTECLIENT?

     public void execute(final Work work) throws IOException {

       ContentExchange exchange = new ContentExchange() {
           protected void onResponseComplete() throws IOException {
               super.onResponseComplete();
               String responseContent = this.getResponseContent();
               work.setFutureResponse(responseContent);
           }
       };
       //set the method and the url
       exchange.setMethod("GET");
       exchange.setURL(work.getUrl());
       // start the exchange
       httpClient.send(exchange);
 }




 12
SO WHY USE AKKA/ACTORS



•     More resource efficient for certain jobs
•     Easier for mere mortals to reason with
•     Nested supervisors can restart failed actors
•     Supports STM if required




 13
THANK YOU

     https://github.com/bloodredsun/ConcurrentWebAppExample



     Email: martin.anderson@betfair.com
     Twitter: @mdjanderson
     Blog: http://bloodredsun.com/
     Betfair Blog: http://views.betfair.com/

14

More Related Content

What's hot

JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesHaim Yadid
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7Mike North
 
Creating custom transformer
Creating custom transformerCreating custom transformer
Creating custom transformerRahul Kumar
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalizationsusant sahu
 
Durable functions
Durable functionsDurable functions
Durable functions명신 김
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Claire Townend Gee
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformLucio Grenzi
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 

What's hot (20)

JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
React hooks
React hooksReact hooks
React hooks
 
Completable future
Completable futureCompletable future
Completable future
 
React hooks
React hooksReact hooks
React hooks
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
React on es6+
React on es6+React on es6+
React on es6+
 
Creating custom transformer
Creating custom transformerCreating custom transformer
Creating custom transformer
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalization
 
Durable functions
Durable functionsDurable functions
Durable functions
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
React hooks
React hooksReact hooks
React hooks
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 

Similar to REPLACING THREADS WITH ACTORS FOR CONCURRENT WEB APPLICATION SERVICE CALLS

Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Morris Singer
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleGeoff Ballinger
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Jalpesh Vadgama
 
Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022David Gómez García
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Jiayun Zhou
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Extending Retrofit for fun and profit
Extending Retrofit for fun and profitExtending Retrofit for fun and profit
Extending Retrofit for fun and profitMatthew Clarke
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadWASdev Community
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkNikos Kalogridis
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)GreeceJS
 

Similar to REPLACING THREADS WITH ACTORS FOR CONCURRENT WEB APPLICATION SERVICE CALLS (20)

Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Extending Retrofit for fun and profit
Extending Retrofit for fun and profitExtending Retrofit for fun and profit
Extending Retrofit for fun and profit
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 Instead
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI framework
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
 

Recently uploaded

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
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
 
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
 
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
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
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
 
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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
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
 
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
 
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
 

Recently uploaded (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
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
 
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
 
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
 
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.
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
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
 
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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
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
 
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
 
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
 

REPLACING THREADS WITH ACTORS FOR CONCURRENT WEB APPLICATION SERVICE CALLS

  • 1. LIGHTNING TALK REPLACING THREADS WITH ACTORS FOR CONCURRENT WEB APPLICATION SERVICE CALLS Martin Anderson LJC Open Conference 2011
  • 2. CONCURRENT SERVICE CALLS •  Most web pages need data from multiple sources •  Scatter/Gather approach to perform all the service calls in parallel then rendering the responses 2
  • 3. CONCURRENCY MODEL dispatch service calls rendering controller’s job starts early done 3
  • 4. THREADS •  Well understood (if not always well implemented!) •  java.util.concurrent library eases the pain •  Resource usage? 4
  • 5. ACTORS •  Been around since 1973 •  Erlang popularised usage •  Actor library for Java? Akka! •  Most strongly associated with Scala but has a Java API 5
  • 6. USING AN EXECUTOR SERVICE IN A SERVLET public void doGet(HttpServletRequest request, HttpServletResponse response) throws…{ List<MyServiceCallable> myServiceCallables = new ArrayList<MyServiceCallable>(); for (int ii = 0; ii < 10; ii++) { myServiceCallables.add(new MyServiceCallablle(remoteClient)); } List<Future<String>> futures = executorService.invokeAll(myServiceCallables); … for (Future future : futures) { writer.write( future.get() ); } … } 6
  • 7. USING AKKA ACTORS IN A SERVLET public void doGet(HttpServletRequest request, HttpServletResponse response) throws…{ Works works = new Works(); for (int ii = 0; ii < 10; ii++) { works.add(new Work())); } masterActor.tell(works); List<Future<String>> futures = works.getFutures(); … for (Future future : futures) { writer.write( future.get() ); } … } 7
  • 8. SO WHAT’S IN AN ACTOR 1? public class MasterActor extends UntypedActor { private ActorRef router; static class LoadBalancer extends UntypedLoadBalancer { private final InfiniteIterator<ActorRef> workers; public LoadBalancer(ActorRef[] workers) { this.workers = new CyclicIterator<ActorRef>(asList(workers)); } public InfiniteIterator<ActorRef> seq() { return workers; } } 8
  • 9. SO WHAT’S IN AN ACTOR 2? public MasterActor(final int numWorkers, final RemoteClient remoteClient) { // create an array of started workers final ActorRef[] workers = new ActorRef[numWorkers]; for (int i = 0; i < numWorkers; i++) { workers[i] = actorOf( new UntypedActorFactory() { public UntypedActor create() { return new WorkerActor(remoteClient); } }) .start(); } // wrap all the workers with a load-balancing router router = actorOf(new UntypedActorFactory() { public UntypedActor create() { return new LoadBalancer(workers); } }).start(); } 9
  • 10. SO WHAT’S IN AN ACTOR 3? // message handler in MasterActor public void onReceive(Object message) { if (message instanceof Works) { for (Work work : ((Works) message).getAll()) { router.tell(work); } } } 10
  • 11. SO WHAT’S IN AN ACTOR 4? public class WorkerActor extends UntypedActor { RemoteClient remoteClient; public WorkerActor(RemoteClient remoteClient) { this.remoteClient = remoteClient; } @Override public void onReceive(Object message) throws Exception { if (message instanceof Work) { Work work = (Work) message; remoteClient.execute(work); } } } 11
  • 12. SO WHAT’S IN OUR REMOTECLIENT? public void execute(final Work work) throws IOException { ContentExchange exchange = new ContentExchange() { protected void onResponseComplete() throws IOException { super.onResponseComplete(); String responseContent = this.getResponseContent(); work.setFutureResponse(responseContent); } }; //set the method and the url exchange.setMethod("GET"); exchange.setURL(work.getUrl()); // start the exchange httpClient.send(exchange); } 12
  • 13. SO WHY USE AKKA/ACTORS •  More resource efficient for certain jobs •  Easier for mere mortals to reason with •  Nested supervisors can restart failed actors •  Supports STM if required 13
  • 14. THANK YOU https://github.com/bloodredsun/ConcurrentWebAppExample Email: martin.anderson@betfair.com Twitter: @mdjanderson Blog: http://bloodredsun.com/ Betfair Blog: http://views.betfair.com/ 14