reactive-with-java8



reactive-with-java8

0 1


reactive-with-java8


On Github markusjura / reactive-with-java8

Going Reactive with Java 8

Markus Jura

About me

  • Trainer @Typesafe
  • Living in Hamburg
  • Co-Founder of testmunk
  • 3 years Scala, 10 years Java background

Agenda

Java 8 Overview

Lambda Overview

Java 7

Runnable r1 = new Runnable() {
  @Override
  public void run() {
    System.out.println("Hello World!");
  }    
};

Java 8

Runnable r2 = () -> System.out.println("Hello World!");

Lambda Examples

// With parameters + multiple lines
button.setOnAction(event -> {
  System.out.println("Thanks for clicking!");
  return event.data;
});

Lambda Method References

Verbose syntax

button.setOnAction(event -> System.out.println(event));

With method reference

button.setOnAction(System.out::println);

Java Streams - Imperative Style

  • Before Java 8: Manipulation of collections trough iterators
  • Explicit looping based on imperative programming paradigm
  • Express how the computer should execute an algorithm
// Calculate Sum of the weights of red blocks
List<Block> blocks = /* ... */;

int sumOfWeights = 0;
for (Block block : blocks) {
  if (block.getColor() == Color.RED) {
    sumOfWeights += block.getWeight();
  }
}

Java Streams - Functional Style

  • Java 8: Manipulation of collections trough Streams
  • Functional programming style
  • Express what the computer should calculate
// Calculate Sum of the weights of red blocks
List<Block> blocks = /* ... */;
int sumOfWeights = blocks.stream() // Stream<Block>
  .filter(b -> b.getColor() == Color.RED)
  .mapToInt(b -> b.getWeight()) // IntStream
  .sum();

Java Streams Operators

  • Intermediate operators:
    • Lazy operation, does not do any transformation immediately
    • map, flatMap, filter
  • Terminal operators
    • Return an actual result
    • Calling a terminal operator executes the stream pipeline
    • forEach, collect, reduce, iterator

Reactive Apps

Users Want Reactive Apps

reactivemanifesto.org

Play & Java 8

Play Features

  • Developer friendly
  • Scaling
  • Modern web & mobile

Routes

Declarative, type-safe URL Mapping

VERB    PATH         CONTROLLER_METHOD

GET     /            controllers.Application.index()
GET     /foo         controllers.Application.foo()

Controllers

  • Synchronous Request
  • Useful for requests that don't block
public static Result index() {
  return ok("Hello World!");
}

Asynchronous Request

import play.libs.F.*;

public static Integer calc() {
    return (5134 * 5789) / 349;
}

public static Promise<Result> basicPromise() { 
  Promise<Integer> promise = Promise.promise(() -> calc()); 
  return promise.map((Integer i) -> ok("Result is: " + i));
}

Webservice Request

  • Client → Server → Service
  • Both async & non-blocking
public static Promise<Result> getPage() { 
  final Promise<WS.Response> promise = 
    WS.url("http://google.com").get();
  return promise.map(response -> ok(response.getBody()));
}

Reactive Composition

  • Three requests, two in parallel (depending on thread availability)
  • All async & non-blocking
public static Promise<Result> composition() { 
  final Promise<WS.Response> googlePromise = 
    WS.url("http://google.com").get();
  final Promise<WS.Response> twitterPromise = 
    WS.url("http://twitter.com").get();

  return googlePromise.flatMap((google) ->
    twitterPromise.map((twitter) ->
      ok(google.getBody() + twitter.getBody())));
}

Reactive Push with SSE

  • Push from Server → Client

CoffeeScript (Client)

events = new EventSource("/events")
events.onmessage = (event) ->
  alert(event.data)

Controller (Server)

public static Result events() {
  return ok(new EventSource() {
    public void onConnected() {
      send(Event.event("hello"));
    }
  });
}

2-Way Reactive with WebSockets I

  • Bi-directional push
    • Server → Client
    • Client → Server

CoffeeScript (Client)

ws = new WebSocket("ws://url/echo")
ws.onmessage = (event) ->
  alert(event.data)

ws.onopen = () ->
  ws.send("Echo")

2-Way Reactive with WebSockets I

Controller (Server)

public static WebSocket<String> echo() {
  return new WebSocket<String>() {
    public void onReady(final In<String> in, 
                        final Out<String> out) {
      in.onMessage(out::write);
    }
  };
}

Akka & Java 8

What is Akka?

Akka is a toolkit and runtime for building highly concurrent, distributed, and fault tolerant event-driven applications on the JVM.

Akka's Value Proposition

A single unified programming model for

  • simpler concurrency
  • simpler distribution
  • simpler fault tolerance

Simpler Concurrency

  • Actors let us write code in a single-threaded illusion
  • No locks, synchronized or other primitives needed

Simpler Distribution

  • Everything in Akka is distributed by default
  • Akka goes from remote to local by optimization

Simpler Fault Tolerance

Akka decouples communication from failure handling:

  • Supervisors handle failure
  • Callers need not care (they can't anyway)

Reactive Stocks Hands-On

Reactive Stocks Architecture

Sources

Get Involved!