Reactive Java
Programming for the
Impatient
—
Mary Grygleski @mgrygles
IBM Developer Advocate
Java
mary.grygleski@ibm.com
Grant Steinfeld @gsteinfeld
IBM Developer Advocate Java &
Blockchain
Agenda
6:30 – 7pm Networking Food
7:00 – 8pm Talk and Demo
8:30 – Q&A + Networking
8:45 – Leave Venue/Doors close
IBM Developer Advocacy - North America East
What is Reactive?
IBM Developer Advocacy - North America East
Organizations working in disparate domains are
independently discovering patterns for building
software that look the same.
These systems are more robust, more resilient,
more flexible and better positioned to meet modern
demands. ... We call these Reactive Systems.
The React i ve
Mani f est o
Published on September 16 2014. (v2.0)
https://www.ReactiveManifesto.org/
Why Reactive?
IBM Developer Advocacy - North America East
Fast is not fast enough!
IBM Developer Advocacy - North America East
Evolving changes and demands in the Computing
Ecosystem
IBM Developer Advocacy - North America East
– Hardware Level
– Software System Level
– Software Application Level
– The impatient User
• “Instantaneous is not fast enough - if no response in <
2 seconds most users under 25 years old will leave the
website/app!”
What is Reactive?
IBM Developer Advocacy - North America East
IBM Developer Advocacy - North America East
Reactive Principles
Important distinctions…
Reactive Programming Functional Reactive
Programming
Reactive Systems and
Architecture
Event-Driven vs Message-Driven
IBM Developer Advocacy - North America East
“An Interesting Reactive
use case:
IBM Developer Advocacy - North America East
Menya Mushashi
Ramen shop in Tokyo
Slow down. Spend more time observing
Reactive Systems : Design Patterns
13
• State Management and Persistence
• Flow Control
• Message Flow
• Fault Tolerance and Recovery
• Replication
• Resource Management
Reactive Microservices vs Monoliths
Isolation of State, Space, Time, Failure
Circuit Breakers
Back –Pressure
High Availability
Eventual Consistency
Reactive Terminology
IBM Developer Advocacy - North America East
What about Microservices?
15
How are Microservices related to Reactive Programming, and
also Reactive Systems?
Rx Marble Diagram
16
Rx Marble Diagram: Map()
17
Observable.just(1, 2, 3)
.map(x -> 10 * x)
.subscribe(x -> Timber.d("item: " + x)));
Output:
item: 10
item: 20
item: 30
Source: https://rxmarbles.com
Reactive Patterns and
Terminologies
* Reactivity
* Events
* Streams
* Observables
DESIGN PATTERNS
Observer
Composite
Iterator
IBM Developer Advocacy - North America East
Reactive – Design Thinking
RxJava
* v1 (pre reactive streams specification) 2014
* v2 2016 (Flowable, with backpressure)
• Java implementation of ReactiveX (reactivex.io)
* Very popular, especially on Android.
•
* Also available in Javascript, .NET, Scala, Clojure, Swift
(and more!) with equivalent API.
IBM Developer Advocacy - North America East
4 Popular Reactive Tools
and Libraries
IBM Developer Advocacy - North America East
• RxJava
• Spring Reactor
• Akka
• Eclipse Vert.x
Fast is not fast
enough!
B
M
D
ev
el
o
p
er
A
dv
oc
ac
N
or
h
A
m
er
c
a
E
as
Code Examples
B
M
D
ev
el
o
p
er
A
dv
oc
ac
N
or
h
A
m
er
c
a
E
as
Simple Example: Hello World
IBM Developer Advocacy - North America East
import reactivex.io.*;
public static void hello(String[] args) {
Flowable.fromArray(args).subscribe(s -> System.out.println("Hello World :: " + s + "!"));
}
IBM Developer Advocacy - North America East
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
public class RxJavaObserverObservable
{
public static void main(String[] args)
{
Observable<String> observable = Observable.just("how", "to", "do", "in", "java");
Consumer<? super String> observer = System.out::println;
observable.subscribe(observer);
}
}
Key Design Pattern: Observer
Spring Reactor
IBM Developer Advocacy - North America East
Based on Project Reactor
Out of Pivotal Labs
Similar to RxJava2
Built for Java 8 ( concise )
Author: David Karnok
Karnok@akarnokd
User Reactor 3
allowed to use Java 8+,
use RxJava 2 if you are
stuck on Java 6+ or need
your functions to throw
checked exceptions
Why?
* Reactor Core
* Reactor Test
* Rector Extra
* Reactor Netty
* Reactor Adapter
* Reactor Kafka
* Reactor RabbitMQ
* Incubating reactive
streams foundation for
.Net, Javascript
Spring 5 Spring Web Reactive ( non-blocking web stack )
//Traditional Approach (Spring MVC):
@GetMapping("/traditional")
public List < Product > getAllProducts() {
List < Product > products = prodService.getProducts("traditional");
return products;
}
//Reactive Approach (Spring Web Reactive – Web Flux):
@GetMapping(value = "/reactive", .TEXT_EVENT_STREAM_VALUE)
public Flux < Product > getAll() {
Flux < Product > fluxProducts = prodService.getProductsStream("Flux");
return fluxProducts;
}
28
Quick comparison: RxJava vs Spring Reactor
Akka
* From LightBend. - IBM Partnership (June 2017)
https://www.lightbend.com/ibm-alliance
* Actor Model (from Erlang – Actor Programming Model in the 1980’s)
* Event-Driven
* Location Transparency
* Lightweight
* Resiliency/Recoverability – Supervisor capability
North America, East
package sample.hello;
public class Main {
public static void main(String[] args) {
akka.Main.main(new String[] { HelloWorld.class.getName() });
}
}
North America, East
31
package sample.hello;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import static sample.hello.Greeter.Msg;
public class HelloWorld extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder()
.matchEquals(Msg.DONE, m -> {
// when the greeter is done, stop this actor and with it the application
getContext().stop(self());
})
.build();
}
@Override
public void preStart() {
// create the greeter actor
final ActorRef greeter = getContext().actorOf(Props.create(Greeter.class), "greeter");
// tell it to perform the greeting
greeter.tell(Msg.GREET, self());
}
}
North America, East
32
package sample.hello;
import akka.actor.AbstractActor;
public class Greeter extends AbstractActor {
public static enum Msg {
GREET, DONE;
}
@Override
public Receive createReceive() {
return receiveBuilder()
.matchEquals(Msg.GREET, m -> {
System.out.println("Hello World!");
sender().tell(Msg.DONE, self());
})
.build();
}
}
North America, East
33
import akka.actor.{Actor, ActorSystem, Props}
//greet message
case class Greet(name: String)
//greeter Actor
class Greeter extends Actor {
def receive = {
case Greet(name) => println(s"Hello $name")
}
}
object HelloAkka extends App {
val system=ActorSystem("Intro-Akka")
val greeter=system.actorOf(Props[Greeter],"greeter")
greeter ! Greet("Akka")
}
North America, East
34
Vert.x
* From Eclipse
* A very flexible “polyglot” framework that interoperates with other frameworks and tools.
-> RxJava
-> Spring Reactor
-> Akka
-> not to mention the other non-Java frameworks and tools as well (JS, .Net…)
* Verticles – components that are being deployed and executed by Vert.x
-> event-driven
-> run only when they receive a message
* Vert.x event bus
* Not restrictively tied to any container – Vert.x libraries can be used with other libraries
North America, East
35
package io.vertx.example;
import io.vertx.core.Vertx;
public class HelloWorldEmbedded {
public static void main(String[] args) {
// Create an HTTP server which simply returns "Hello World!" to each request.
Vertx.vertx().createHttpServer().requestHandler(req -> req.response().end("Hello
World!")).listen(8080);
}
North America, East
Recap and Takeaways
IBM Developer Advocacy - North America East
• Reactive is an overloaded word in today’s market
• Not for the ”faint of heart” but for the determined
• Reactive programming is not the same as Functional
• Reactive programming or Reactive systems
• Benefits of being “Reactive” on the programming level
• Reactive systems and architecture bring “reactivity” to
another level
• Reactivity to this day has not been fully ready on the
database level, despite some significant efforts on the
database connectivity level
Thank You
IBM Developer Advocacy - North America East
twitter.com/mgrygles
twitter.com/gsteinfeld
github.com/mgrygles
github.com/grant-steinfeld
Resources
https://developer.ibm.com/technologies/reactive-
systems/
https://www.lightbend.com/ibm-alliancec
https://www.reactivemanifesto.org
https://www.reactivedesignpatterns.com
IBM Developer Advocacy - North America East
Check in periodically at https://developer.ibm.com/events/
Join us for more exciting
adventures in async.
meetups, workshops, coffee
and code sessions.
IBM Developer Advocacy - North America East

Reactive java programming for the impatient

  • 1.
    Reactive Java Programming forthe Impatient — Mary Grygleski @mgrygles IBM Developer Advocate Java mary.grygleski@ibm.com Grant Steinfeld @gsteinfeld IBM Developer Advocate Java & Blockchain
  • 2.
    Agenda 6:30 – 7pmNetworking Food 7:00 – 8pm Talk and Demo 8:30 – Q&A + Networking 8:45 – Leave Venue/Doors close IBM Developer Advocacy - North America East
  • 3.
    What is Reactive? IBMDeveloper Advocacy - North America East Organizations working in disparate domains are independently discovering patterns for building software that look the same. These systems are more robust, more resilient, more flexible and better positioned to meet modern demands. ... We call these Reactive Systems. The React i ve Mani f est o Published on September 16 2014. (v2.0) https://www.ReactiveManifesto.org/
  • 4.
    Why Reactive? IBM DeveloperAdvocacy - North America East
  • 5.
    Fast is notfast enough! IBM Developer Advocacy - North America East
  • 6.
    Evolving changes anddemands in the Computing Ecosystem IBM Developer Advocacy - North America East – Hardware Level – Software System Level – Software Application Level – The impatient User • “Instantaneous is not fast enough - if no response in < 2 seconds most users under 25 years old will leave the website/app!”
  • 7.
    What is Reactive? IBMDeveloper Advocacy - North America East
  • 8.
    IBM Developer Advocacy- North America East Reactive Principles
  • 9.
    Important distinctions… Reactive ProgrammingFunctional Reactive Programming Reactive Systems and Architecture
  • 10.
    Event-Driven vs Message-Driven IBMDeveloper Advocacy - North America East
  • 11.
    “An Interesting Reactive usecase: IBM Developer Advocacy - North America East Menya Mushashi Ramen shop in Tokyo
  • 12.
    Slow down. Spendmore time observing
  • 13.
    Reactive Systems :Design Patterns 13 • State Management and Persistence • Flow Control • Message Flow • Fault Tolerance and Recovery • Replication • Resource Management
  • 14.
    Reactive Microservices vsMonoliths Isolation of State, Space, Time, Failure Circuit Breakers Back –Pressure High Availability Eventual Consistency Reactive Terminology IBM Developer Advocacy - North America East
  • 15.
    What about Microservices? 15 Howare Microservices related to Reactive Programming, and also Reactive Systems?
  • 16.
  • 17.
    Rx Marble Diagram:Map() 17 Observable.just(1, 2, 3) .map(x -> 10 * x) .subscribe(x -> Timber.d("item: " + x))); Output: item: 10 item: 20 item: 30 Source: https://rxmarbles.com
  • 18.
    Reactive Patterns and Terminologies *Reactivity * Events * Streams * Observables DESIGN PATTERNS Observer Composite Iterator IBM Developer Advocacy - North America East
  • 19.
  • 20.
    RxJava * v1 (prereactive streams specification) 2014 * v2 2016 (Flowable, with backpressure) • Java implementation of ReactiveX (reactivex.io) * Very popular, especially on Android. • * Also available in Javascript, .NET, Scala, Clojure, Swift (and more!) with equivalent API. IBM Developer Advocacy - North America East
  • 21.
    4 Popular ReactiveTools and Libraries IBM Developer Advocacy - North America East • RxJava • Spring Reactor • Akka • Eclipse Vert.x
  • 22.
    Fast is notfast enough! B M D ev el o p er A dv oc ac N or h A m er c a E as
  • 23.
  • 24.
    Simple Example: HelloWorld IBM Developer Advocacy - North America East import reactivex.io.*; public static void hello(String[] args) { Flowable.fromArray(args).subscribe(s -> System.out.println("Hello World :: " + s + "!")); }
  • 25.
    IBM Developer Advocacy- North America East import io.reactivex.Observable; import io.reactivex.functions.Consumer; public class RxJavaObserverObservable { public static void main(String[] args) { Observable<String> observable = Observable.just("how", "to", "do", "in", "java"); Consumer<? super String> observer = System.out::println; observable.subscribe(observer); } } Key Design Pattern: Observer
  • 26.
    Spring Reactor IBM DeveloperAdvocacy - North America East Based on Project Reactor Out of Pivotal Labs Similar to RxJava2 Built for Java 8 ( concise ) Author: David Karnok Karnok@akarnokd User Reactor 3 allowed to use Java 8+, use RxJava 2 if you are stuck on Java 6+ or need your functions to throw checked exceptions Why? * Reactor Core * Reactor Test * Rector Extra * Reactor Netty * Reactor Adapter * Reactor Kafka * Reactor RabbitMQ * Incubating reactive streams foundation for .Net, Javascript
  • 27.
    Spring 5 SpringWeb Reactive ( non-blocking web stack ) //Traditional Approach (Spring MVC): @GetMapping("/traditional") public List < Product > getAllProducts() { List < Product > products = prodService.getProducts("traditional"); return products; } //Reactive Approach (Spring Web Reactive – Web Flux): @GetMapping(value = "/reactive", .TEXT_EVENT_STREAM_VALUE) public Flux < Product > getAll() { Flux < Product > fluxProducts = prodService.getProductsStream("Flux"); return fluxProducts; }
  • 28.
    28 Quick comparison: RxJavavs Spring Reactor
  • 29.
    Akka * From LightBend.- IBM Partnership (June 2017) https://www.lightbend.com/ibm-alliance * Actor Model (from Erlang – Actor Programming Model in the 1980’s) * Event-Driven * Location Transparency * Lightweight * Resiliency/Recoverability – Supervisor capability North America, East
  • 30.
    package sample.hello; public classMain { public static void main(String[] args) { akka.Main.main(new String[] { HelloWorld.class.getName() }); } } North America, East
  • 31.
    31 package sample.hello; import akka.actor.AbstractActor; importakka.actor.ActorRef; import akka.actor.Props; import static sample.hello.Greeter.Msg; public class HelloWorld extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() .matchEquals(Msg.DONE, m -> { // when the greeter is done, stop this actor and with it the application getContext().stop(self()); }) .build(); } @Override public void preStart() { // create the greeter actor final ActorRef greeter = getContext().actorOf(Props.create(Greeter.class), "greeter"); // tell it to perform the greeting greeter.tell(Msg.GREET, self()); } } North America, East
  • 32.
    32 package sample.hello; import akka.actor.AbstractActor; publicclass Greeter extends AbstractActor { public static enum Msg { GREET, DONE; } @Override public Receive createReceive() { return receiveBuilder() .matchEquals(Msg.GREET, m -> { System.out.println("Hello World!"); sender().tell(Msg.DONE, self()); }) .build(); } } North America, East
  • 33.
    33 import akka.actor.{Actor, ActorSystem,Props} //greet message case class Greet(name: String) //greeter Actor class Greeter extends Actor { def receive = { case Greet(name) => println(s"Hello $name") } } object HelloAkka extends App { val system=ActorSystem("Intro-Akka") val greeter=system.actorOf(Props[Greeter],"greeter") greeter ! Greet("Akka") } North America, East
  • 34.
    34 Vert.x * From Eclipse *A very flexible “polyglot” framework that interoperates with other frameworks and tools. -> RxJava -> Spring Reactor -> Akka -> not to mention the other non-Java frameworks and tools as well (JS, .Net…) * Verticles – components that are being deployed and executed by Vert.x -> event-driven -> run only when they receive a message * Vert.x event bus * Not restrictively tied to any container – Vert.x libraries can be used with other libraries North America, East
  • 35.
    35 package io.vertx.example; import io.vertx.core.Vertx; publicclass HelloWorldEmbedded { public static void main(String[] args) { // Create an HTTP server which simply returns "Hello World!" to each request. Vertx.vertx().createHttpServer().requestHandler(req -> req.response().end("Hello World!")).listen(8080); } North America, East
  • 36.
    Recap and Takeaways IBMDeveloper Advocacy - North America East • Reactive is an overloaded word in today’s market • Not for the ”faint of heart” but for the determined • Reactive programming is not the same as Functional • Reactive programming or Reactive systems • Benefits of being “Reactive” on the programming level • Reactive systems and architecture bring “reactivity” to another level • Reactivity to this day has not been fully ready on the database level, despite some significant efforts on the database connectivity level
  • 37.
    Thank You IBM DeveloperAdvocacy - North America East twitter.com/mgrygles twitter.com/gsteinfeld github.com/mgrygles github.com/grant-steinfeld
  • 38.
  • 39.
    Check in periodicallyat https://developer.ibm.com/events/ Join us for more exciting adventures in async. meetups, workshops, coffee and code sessions. IBM Developer Advocacy - North America East

Editor's Notes

  • #4 Asynchronous Backends
  • #14 State management and persistence patterns Domain object Sharding Event sourcing Event stream Flow control patterns Pull Managed queue Drop Throttling Message flow patterns Request–response Self-contained message Ask pattern Forward Flow Aggregator Saga Business Handshake Fault tolerance and recovery patterns Simple Component Error Kernel Let-it-crash Circuit Breaker Replication patterns Active–passive Multiple-master Consensus-based Conflict detection and resolution Conflict-free replicated data types Active–active Resource management patterns Resource encapsulation Resource loan Complex command Resource pool Managed blocking