SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Multi-threading in the
Modern Era
Multi-threading
• Multi-threading in Java (and in general) is extremely hard!
• Reasons:
• Race-conditions.
• Deadlocks.
• Starvation.
Multi-threading in Java
• The standard-libraries provide us with excellent low-level
mechanisms to deal with multi-threading scenarios:
• volatile.
• synchronized.
• java.util.concurrent.
• Futures/ CompletableFutures/ Atomic Classes/ etc…
Performance
• Usually, when doing low-level synchronization, we encounter
multiple performance issues!
• All stems from shared mutable state!
Node.js
• On the other hand, a popular non-Java framework, Node.js,
started gaining a lot of attention due to its “simplicity” and
“performance”.
• And you only have a single main thread for your application.
• (yes, there are multiple background threads in Node.js).
Shared Mutable State
• The core reason is that we don’t have shared-mutable state that
requires locking and synchronization!
• The problem can be solved by one of the following:
• All data is immutable (extremely hard in Java).
• Unshared mutable data.
Unshared Mutable State
• We are going to discuss unshared mutable state.
• Usually it is provided by frameworks.
• The concept is very old in Java and the most infamous
framework that provided it was EJB.
• We’ll cover, in this session, the modern frameworks:
• Akka.
• Vert.x.
• Quasar.
Akka
• Akka is an open source framework for building highly
concurrent, distributed and fault-tolerant applications.
• Written in Scala and provides a decent Java API.
• Based on the famous actor model from Erlang.
Actors
• An actor is a message processor which processes messages
asynchronously (usually in a different thread).
• Let’s take a look at an actor…
Actor
• To create an actor, you should extend from the UntypedActor
class.
public class SimpleActor extends UntypedActor {
@Override
public void onReceive(Object message) {
System.out.println("Got: " + message);
}
}
class SimpleActor extends Actor {
def receive = {
case msg => println(s"Got: $msg")
}
}
Creating Actors
• You must never instantiate actors yourself.
• You should never hold a direct reference to the actor.
• Only Akka does.
• It ensures that mutable members inside the actor are properly
encapsulated and unshared.
• In order to instantiate an actor, we need to work with the
ActorSystem object.
Actor
• ActorSystem represents a logical application.
• A configuration environment.
• Creating an ActorSystem (usually one in your app):
ActorSystem as = ActorSystem.create("WelcomeToAkka");
val as = ActorSystem("WelcomeToAkka")
actorOf
• The actorOf method creates a new actor:
ActorRef ref = as.actorOf(Props.create(SimpleActor.class),
"simpleActor");
val ref = as.actorOf(Props[SimpleActor], "simpleActor")
• Note the return type.
• It’s ActorRef and not our actor class.
ActorRef
• Represents a reference to the actor.
• It is immutable and location transparent.
• Can be sent around in messages.
• Can be obtained for remote/clustered actors.
• Its most useful API: sending a message.
Fire and Forget
• Sending a message is done in an asynchronous manner.
• The tell() method sends a message to the actor:
ref.tell("Hello from Main", ActorRef.noSender());
// no need to specify sender, it is Actor.noSender (default param)
ref ! "Hello"
• The message must be immutable!
Handling Messages
• If the message is unknown, you should call: unhandled().
• It will send an UnhandledMessage instance to the eventStream.
public void onReceive(Object message) throws Exception {
if (message instanceof String) {
System.out.println("Got: " + message);
} else {
unhandled(message);
}
}
Routers
• Routers are actors that dispatch incoming messages to their
routees.
• Implementations available: RoundRobin, RandomRobin,
Broadcast, ConsistentHashing and more.
More Features
• Clustering.
• Persistence.
• Sharding.
• Singletons.
• Distributed Event Streams.
• FSM.
Vert.x
• “Eclipse Vert.x is a tool-kit for building reactive applications on
the JVM.”
• At the core of Vert.x is the reactor pattern (a.k.a. event-loop).
• By default, Vert.x spawns N*2 (where N being the number of
cores) event-loop threads.
• The event-loop thread is responsible for calling your handlers
when there are events.
• Don’t ever block it!
Vertx Instances
• At the low level API there is the Vertx instance.
• Usually one in your application.
• Contains several event-loop threads.
• Can be clustered.
Vertx vertx = Vertx.vertx();
Verticles
• Usually you’ll work with Verticles (which resemble actors).
• Come in 3 flavors:
• Standard verticles.
• Worker verticles.
• Multi-threaded worker verticles.
• We’ll focus here on standard verticles.
Standard Verticle
• A standard verticle is assigned to a specific event-loop thread.
• It means that your verticle code can be written without
synchronization or lock management.
• However, how to perform I/O?
• Use Vert.x provided APIs.
The Event Bus
• Each Vertx instance has an event bus.
• Through it, different verticles can communicate.
• Supports both publish-subscribe and point-to-point.
Async Ops
• Vert.x provides many wrappers and utilities for I/O operations:
• HTTP (server and client).
• Scheduling.
• JDBC.
• NoSQL DBs.
• Mail.
• RabbitMQ.
• STOMP.
• Kafka.
Example
• Here is an example of sending an HTTP request (HTTP client).
HttpClient client = vertx.createHttpClient();
client.getNow(8080, "trainologic.com", "/technologies/java/", response ->
{
System.out.println("Trainologic Java status code: " +
response.statusCode());
}
);
Clustering
• Vert.x provides clustering support out of the box.
• The event-bus can be clustered.
Quasar
• Quasar aims to provide a simple and performant multi-threading
solution by providing “green-threads”.
• Green threads (called fibers in Quasar jargon) are user-space
threads which have no overhead.
• They actually shared the Thread API thus enabling abstraction
over kernel/user threads.
Fibers
• Fibers allow you to avoid the callback hell.
• So, if you have an interface with blocking API:
• String foo(int i);
• Fiber implementation:
@Suspendable
public int foo(final String arg) throws IOException, InterruptedException {
try { return new FiberAsync<Integer, IOException>() {
@Override
protected void requestAsync() {
asyncAPI.asyncInvocation(arg, new SomeHandler<Integer>() {
public void success(Integer result) {
asyncCompleted(result);
}
…
How Does it Work?
• Fibers are implemented by continuations!
• The ability to suspend and snapshot the stack of the execution.
• Allowing for cheap context-switching.
• Quasar can do it with either build-time instrumentation or
dedicated Java-agent.
• Don’t forget to mark “blocking” methods as @Suspendable!
Features
• Quasar provides:
• Languages: Java, Kotlin & Clojure.
• Good Actor System.
• Clustering (Galaxy) – basic support.
• Integration with Web (Comsat). E.g.:
• HTTP
• Spring
• Kafka
• Servlet Containers…
Discussion
• Maturity – Akka and Vert.x quite mature.
• Features – Akka provides the most complete solution. Can be a
bit harder in Java than Vert.x.
• Simplicity – Quasar offers the most “readable” and simple
solution.
• Performance – May vary. All can be very performant!
• Design – all affect your application on the whole!!
Conclusion
• Concurrency is hard!
• Shared mutable state is hard!
• Non-blocking is hard!
• Perhaps going immutable and pure-functional is the way?

Weitere ähnliche Inhalte

Was ist angesagt?

Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterKonstantin Tsykulenko
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterKonstantin Tsykulenko
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuHavoc Pennington
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesLightbend
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentationGene Chang
 
Spring Boot Microservices vs Akka Actor Cluster
Spring Boot Microservices vs Akka Actor Cluster Spring Boot Microservices vs Akka Actor Cluster
Spring Boot Microservices vs Akka Actor Cluster OpenCredo
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in ScalaAlex Payne
 
Introduction to akka actors with java 8
Introduction to akka actors with java 8Introduction to akka actors with java 8
Introduction to akka actors with java 8Johan Andrén
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayYardena Meymann
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayRoland Kuhn
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsGo Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsJonas Bonér
 
Akka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaAkka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaJerry Kuru
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupRoy Russo
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений БобровFwdays
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camelkrasserm
 
Lightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just RightLightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just Rightmircodotta
 
Akka Cluster in Production
Akka Cluster in ProductionAkka Cluster in Production
Akka Cluster in Productionbilyushonak
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den HoekRubiX BV
 

Was ist angesagt? (20)

Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Spring Boot Microservices vs Akka Actor Cluster
Spring Boot Microservices vs Akka Actor Cluster Spring Boot Microservices vs Akka Actor Cluster
Spring Boot Microservices vs Akka Actor Cluster
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in Scala
 
Introduction to akka actors with java 8
Introduction to akka actors with java 8Introduction to akka actors with java 8
Introduction to akka actors with java 8
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive Way
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsGo Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
 
Akka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaAkka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with Scala
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
 
System Integration with Akka and Apache Camel
System Integration with Akka and Apache CamelSystem Integration with Akka and Apache Camel
System Integration with Akka and Apache Camel
 
Lightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just RightLightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just Right
 
Akka Cluster in Production
Akka Cluster in ProductionAkka Cluster in Production
Akka Cluster in Production
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den Hoek
 

Ähnlich wie Multi-threading in the modern era: Vertx Akka and Quasar

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debuggerIulian Dragos
 
Building Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaBuilding Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaWO Community
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayLuka Zakrajšek
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysManuel Bernhardt
 
Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuSalesforce Developers
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java introkabirmahlotra
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java introkabirmahlotra
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsSerge Stinckwich
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksWO Community
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Javaforum 20110915
Javaforum 20110915Javaforum 20110915
Javaforum 20110915Squeed
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediZeroTurnaround
 

Ähnlich wie Multi-threading in the modern era: Vertx Akka and Quasar (20)

Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Building Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaBuilding Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with Scala
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Akka.Net Overview
Akka.Net OverviewAkka.Net Overview
Akka.Net Overview
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
 
Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and Heroku
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java intro
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java intro
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systems
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Javaforum 20110915
Javaforum 20110915Javaforum 20110915
Javaforum 20110915
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 

Kürzlich hochgeladen

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Kürzlich hochgeladen (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Multi-threading in the modern era: Vertx Akka and Quasar

  • 2. Multi-threading • Multi-threading in Java (and in general) is extremely hard! • Reasons: • Race-conditions. • Deadlocks. • Starvation.
  • 3. Multi-threading in Java • The standard-libraries provide us with excellent low-level mechanisms to deal with multi-threading scenarios: • volatile. • synchronized. • java.util.concurrent. • Futures/ CompletableFutures/ Atomic Classes/ etc…
  • 4. Performance • Usually, when doing low-level synchronization, we encounter multiple performance issues! • All stems from shared mutable state!
  • 5. Node.js • On the other hand, a popular non-Java framework, Node.js, started gaining a lot of attention due to its “simplicity” and “performance”. • And you only have a single main thread for your application. • (yes, there are multiple background threads in Node.js).
  • 6. Shared Mutable State • The core reason is that we don’t have shared-mutable state that requires locking and synchronization! • The problem can be solved by one of the following: • All data is immutable (extremely hard in Java). • Unshared mutable data.
  • 7. Unshared Mutable State • We are going to discuss unshared mutable state. • Usually it is provided by frameworks. • The concept is very old in Java and the most infamous framework that provided it was EJB. • We’ll cover, in this session, the modern frameworks: • Akka. • Vert.x. • Quasar.
  • 8. Akka • Akka is an open source framework for building highly concurrent, distributed and fault-tolerant applications. • Written in Scala and provides a decent Java API. • Based on the famous actor model from Erlang.
  • 9. Actors • An actor is a message processor which processes messages asynchronously (usually in a different thread). • Let’s take a look at an actor…
  • 10. Actor • To create an actor, you should extend from the UntypedActor class. public class SimpleActor extends UntypedActor { @Override public void onReceive(Object message) { System.out.println("Got: " + message); } } class SimpleActor extends Actor { def receive = { case msg => println(s"Got: $msg") } }
  • 11. Creating Actors • You must never instantiate actors yourself. • You should never hold a direct reference to the actor. • Only Akka does. • It ensures that mutable members inside the actor are properly encapsulated and unshared. • In order to instantiate an actor, we need to work with the ActorSystem object.
  • 12. Actor • ActorSystem represents a logical application. • A configuration environment. • Creating an ActorSystem (usually one in your app): ActorSystem as = ActorSystem.create("WelcomeToAkka"); val as = ActorSystem("WelcomeToAkka")
  • 13. actorOf • The actorOf method creates a new actor: ActorRef ref = as.actorOf(Props.create(SimpleActor.class), "simpleActor"); val ref = as.actorOf(Props[SimpleActor], "simpleActor") • Note the return type. • It’s ActorRef and not our actor class.
  • 14. ActorRef • Represents a reference to the actor. • It is immutable and location transparent. • Can be sent around in messages. • Can be obtained for remote/clustered actors. • Its most useful API: sending a message.
  • 15. Fire and Forget • Sending a message is done in an asynchronous manner. • The tell() method sends a message to the actor: ref.tell("Hello from Main", ActorRef.noSender()); // no need to specify sender, it is Actor.noSender (default param) ref ! "Hello" • The message must be immutable!
  • 16. Handling Messages • If the message is unknown, you should call: unhandled(). • It will send an UnhandledMessage instance to the eventStream. public void onReceive(Object message) throws Exception { if (message instanceof String) { System.out.println("Got: " + message); } else { unhandled(message); } }
  • 17. Routers • Routers are actors that dispatch incoming messages to their routees. • Implementations available: RoundRobin, RandomRobin, Broadcast, ConsistentHashing and more.
  • 18. More Features • Clustering. • Persistence. • Sharding. • Singletons. • Distributed Event Streams. • FSM.
  • 19. Vert.x • “Eclipse Vert.x is a tool-kit for building reactive applications on the JVM.” • At the core of Vert.x is the reactor pattern (a.k.a. event-loop). • By default, Vert.x spawns N*2 (where N being the number of cores) event-loop threads. • The event-loop thread is responsible for calling your handlers when there are events. • Don’t ever block it!
  • 20. Vertx Instances • At the low level API there is the Vertx instance. • Usually one in your application. • Contains several event-loop threads. • Can be clustered. Vertx vertx = Vertx.vertx();
  • 21. Verticles • Usually you’ll work with Verticles (which resemble actors). • Come in 3 flavors: • Standard verticles. • Worker verticles. • Multi-threaded worker verticles. • We’ll focus here on standard verticles.
  • 22. Standard Verticle • A standard verticle is assigned to a specific event-loop thread. • It means that your verticle code can be written without synchronization or lock management. • However, how to perform I/O? • Use Vert.x provided APIs.
  • 23. The Event Bus • Each Vertx instance has an event bus. • Through it, different verticles can communicate. • Supports both publish-subscribe and point-to-point.
  • 24. Async Ops • Vert.x provides many wrappers and utilities for I/O operations: • HTTP (server and client). • Scheduling. • JDBC. • NoSQL DBs. • Mail. • RabbitMQ. • STOMP. • Kafka.
  • 25. Example • Here is an example of sending an HTTP request (HTTP client). HttpClient client = vertx.createHttpClient(); client.getNow(8080, "trainologic.com", "/technologies/java/", response -> { System.out.println("Trainologic Java status code: " + response.statusCode()); } );
  • 26. Clustering • Vert.x provides clustering support out of the box. • The event-bus can be clustered.
  • 27. Quasar • Quasar aims to provide a simple and performant multi-threading solution by providing “green-threads”. • Green threads (called fibers in Quasar jargon) are user-space threads which have no overhead. • They actually shared the Thread API thus enabling abstraction over kernel/user threads.
  • 28. Fibers • Fibers allow you to avoid the callback hell. • So, if you have an interface with blocking API: • String foo(int i); • Fiber implementation: @Suspendable public int foo(final String arg) throws IOException, InterruptedException { try { return new FiberAsync<Integer, IOException>() { @Override protected void requestAsync() { asyncAPI.asyncInvocation(arg, new SomeHandler<Integer>() { public void success(Integer result) { asyncCompleted(result); } …
  • 29. How Does it Work? • Fibers are implemented by continuations! • The ability to suspend and snapshot the stack of the execution. • Allowing for cheap context-switching. • Quasar can do it with either build-time instrumentation or dedicated Java-agent. • Don’t forget to mark “blocking” methods as @Suspendable!
  • 30. Features • Quasar provides: • Languages: Java, Kotlin & Clojure. • Good Actor System. • Clustering (Galaxy) – basic support. • Integration with Web (Comsat). E.g.: • HTTP • Spring • Kafka • Servlet Containers…
  • 31. Discussion • Maturity – Akka and Vert.x quite mature. • Features – Akka provides the most complete solution. Can be a bit harder in Java than Vert.x. • Simplicity – Quasar offers the most “readable” and simple solution. • Performance – May vary. All can be very performant! • Design – all affect your application on the whole!!
  • 32. Conclusion • Concurrency is hard! • Shared mutable state is hard! • Non-blocking is hard! • Perhaps going immutable and pure-functional is the way?