socal code camp 2015: an introduction to java 8

72
Java 8 Level Up with new features! 1 Socal Code Camp 2015 14 Nov, Los Angeles

Upload: chaitanya-ganoo

Post on 13-Apr-2017

400 views

Category:

Engineering


2 download

TRANSCRIPT

Page 1: SoCal Code Camp 2015: An introduction to Java 8

1

Java 8Level Up with new features!

Socal Code Camp 201514 Nov, Los Angeles

Page 2: SoCal Code Camp 2015: An introduction to Java 8

2

Java 8Level Up with new features!

Image: http://blog.takipi.com/

Page 3: SoCal Code Camp 2015: An introduction to Java 8

3

Who am I?

@cganoo@cganoo

Trademarks and pictures belong to respective copyright owners

@caganoo

Page 4: SoCal Code Camp 2015: An introduction to Java 8

4

Agenda

Introduction

Default Methods

Lambdas

Streams

CompletableFuture

Demo

Page 5: SoCal Code Camp 2015: An introduction to Java 8

5

Intro

Popularity Rank on GitHub

Popu

larit

y Ra

nk o

n St

ackO

verfl

ow

https://redmonk.com/sogrady/2015/07/01/language-rankings-6-15/

Page 6: SoCal Code Camp 2015: An introduction to Java 8

6

Intro

https://dzone.com/articles/java-version-statistics-2015http://www.oracle.com/technetwork/java/eol-135779.html

Page 7: SoCal Code Camp 2015: An introduction to Java 8

7

Default Methods

Interview Question:

What is an interface in java?

Page 8: SoCal Code Camp 2015: An introduction to Java 8

8

Default Methods

Interfaces can now declare methods with implementation: Static methods Default Methods

Page 9: SoCal Code Camp 2015: An introduction to Java 8

9

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

Page 10: SoCal Code Camp 2015: An introduction to Java 8

10

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

Collections.sort(numbers);

Page 11: SoCal Code Camp 2015: An introduction to Java 8

11

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

Collections.sort(numbers);

Collections.sort(numbers, myComparator);

Page 12: SoCal Code Camp 2015: An introduction to Java 8

12

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

numbers.sort(Comparator.naturalOrder());

Page 13: SoCal Code Camp 2015: An introduction to Java 8

13

Default Methods

Page 14: SoCal Code Camp 2015: An introduction to Java 8

14

Default Methodspublic class Dog implements Bark {

// No overridden method}

public interface Bark { default String bark() { return "Woof Woof!"; }}

public static void main(String[] args) { Dog dog = new Dog(); dog.bark(); // Woof Woof!}

Page 15: SoCal Code Camp 2015: An introduction to Java 8

15

Default Methods

Interview Question:

What's the difference between Abstract classes and Interfaces?

Page 16: SoCal Code Camp 2015: An introduction to Java 8

16

Default Methods

Page 17: SoCal Code Camp 2015: An introduction to Java 8

17

Default Methods

3 Resolution Rules:

Classes always win Then, sub-interfaces win Then, the inheriting class inheriting has to

explicitly select

Page 18: SoCal Code Camp 2015: An introduction to Java 8

18

Lambdas

Image: http://blog.takipi.com/

Page 19: SoCal Code Camp 2015: An introduction to Java 8

19

Lambdas

Concise way to express Behavior Parametrization

Page 20: SoCal Code Camp 2015: An introduction to Java 8

20

LambdasList<Student> filterByGrade(students, grade) {

List<Student> result = new ArrayList<>();

for (Student student : students) {if

( student.getGrade().equals(grade) ) {result.add(student);

}}return result;

}

Page 21: SoCal Code Camp 2015: An introduction to Java 8

21

Lambdas

List<Student> gradeAStudents = filterByGrade(students, "A");

List<Student> gradeBStudents = filterByGrade(students, "B");

Page 22: SoCal Code Camp 2015: An introduction to Java 8

22

LambdasList<Student> filterByAge(students, age) {

List<Student> result = new ArrayList<>();

for (Student student : students) {if ( student.getAge() > age ) {

result.add(student);}

}return result;

}

Page 23: SoCal Code Camp 2015: An introduction to Java 8

23

Lambdas

List<Student> oldStudents = filterByAge(students, 30);

List<Student> youngStudents = filterByAge(students, 20);

Value Parameterization!

Page 24: SoCal Code Camp 2015: An introduction to Java 8

24

Lambdaspublic interface Predicate<T> {

boolean test(T t);}

List<T> filter(List<T> list, Predicate<T> p) {

List<T> result = new ArrayList<>();for(T e: list) {

if(p.test(e)){ result.add(e); }}return result;

}

Page 25: SoCal Code Camp 2015: An introduction to Java 8

25

Lambdas

filter( students,

(Student s) -> "A".equals(s.getGrade()));

Page 26: SoCal Code Camp 2015: An introduction to Java 8

26

LambdasComparator<Student> c = new Comparator<Student>() {

public int compare(Student a1, Student a2) {

return a1.getAge().compareTo(a2.getAge());

}};

Page 27: SoCal Code Camp 2015: An introduction to Java 8

27

LambdasComparator<Student> c = new Comparator<Student>() {

public int compare(Student a1, Student a2) {

return a1.getAge().compareTo(a2.getAge());

}};

Comparator<Student> c = (Student a1, Student a2) -> a1.getGrade().compareTo(a2.getGrade());

Page 28: SoCal Code Camp 2015: An introduction to Java 8

28

Lambdas

So where can you use lambdas?

In the context of a functional interface

Page 29: SoCal Code Camp 2015: An introduction to Java 8

29

Lambdas

A functional interface is an interface that specifies exactly one abstractmethod

Page 30: SoCal Code Camp 2015: An introduction to Java 8

30

Lambdas@FunctionalInterfacepublic interface Runnable {

public abstract void run();}

@FunctionalInterfacepublic interface Callable<V> {

V call() throws Exception;}

Page 31: SoCal Code Camp 2015: An introduction to Java 8

31

Lambdas

Thread thread1 = new Thread(new Runnable() { @Override public void run(){ doSomething(); }}); thread1.start();

Page 32: SoCal Code Camp 2015: An introduction to Java 8

32

Lambdas

Thread thread1 = new Thread(new Runnable() { @Override public void run(){ doSomething(); }}); thread1.start();

new Thread(() -> doSomething()).start();

Page 33: SoCal Code Camp 2015: An introduction to Java 8

33

Lambdas@FunctionalInterfacepublic interface Predicate<T> {

boolean test(T t);}

@FunctionalInterfacepublic interface Function<T, R> {

R apply(T t);}

Page 34: SoCal Code Camp 2015: An introduction to Java 8

34

Lambdas

Method References:

items.forEach((x) -> System.out.print(x));

items.forEach(System.out::print);

Page 35: SoCal Code Camp 2015: An introduction to Java 8

35

Lambdas

Image taken from the book ‘Java 8 in Action’ by Urma, Fusco and Mycroft

Page 36: SoCal Code Camp 2015: An introduction to Java 8

36

Streams

Image: http://www.123rf.com/photo_5391089_blue-tsunami-wave-two.html

Page 37: SoCal Code Camp 2015: An introduction to Java 8

37

Streams

Stream is a sequence of elements from a source that supports data processing operations

Page 38: SoCal Code Camp 2015: An introduction to Java 8

38

StreamsMotivation: Collections is the most heavily used API in

Java

Page 39: SoCal Code Camp 2015: An introduction to Java 8

39

StreamsMotivation: Collections is the most heavily used API in

Java Lacks declarative syntax

Page 40: SoCal Code Camp 2015: An introduction to Java 8

40

StreamsMotivation: Collections is the most heavily used API in

Java Lacks declarative syntax Lacks easy parallelization API

Page 41: SoCal Code Camp 2015: An introduction to Java 8

41

Streams

Stream is a sequence of elements from a source that supports data processing operations:

Fancy iterators that let you manipulate collections of data in a declarative, composable and transparently parallel way

Page 42: SoCal Code Camp 2015: An introduction to Java 8

42

Streams

Streams are Collections on steroids!

Page 43: SoCal Code Camp 2015: An introduction to Java 8

43

Streams

List<String> someStudentNames =students.stream()

.filter(s -> s.getAge() > 20)

.sorted(comparing(Student::getGrade)).map(Student::getName).collect(toList());

Page 44: SoCal Code Camp 2015: An introduction to Java 8

44

Streams

List<Student> someStudents =students.stream()

.filter(s -> s.getAge() > 20)

.sorted(comparing(Student::getGrade)).map(Student::getName).collect(toList());Get a list of the names of all students, sorted by their

grades and who are above 20 years of age

Page 45: SoCal Code Camp 2015: An introduction to Java 8

45

Streams

List<Student> someStudents =students.parallelStream()

.filter(s -> s.getAge() > 20)

.sorted(comparing(Student::getGrade)).map(Student::getName).collect(toList());Get a list of the names of all students, sorted by their

grades and who are above 20 years of age

Page 46: SoCal Code Camp 2015: An introduction to Java 8

46

StreamsIntermediate Operations: Return Stream<X>

filter Predicate<T> T -> booleanmap Function<T, R> T -> Rsorted Comparator<T> (T, T) -> intdistinct

Page 47: SoCal Code Camp 2015: An introduction to Java 8

47

StreamsTerminal Operations:

forEach Consumer<T> T -> voidcount Returns a longcollect Collector<T, A, R> reduce T identity, BinaryOperator<T>

Page 48: SoCal Code Camp 2015: An introduction to Java 8

48

Streams

Generating Streams:

Stream.of("Code", "Camp")

Arrays.stream(new int[] {1, 2})

Files.lines() (Java NIO)

Page 49: SoCal Code Camp 2015: An introduction to Java 8

49

Streams

Generating Infinite Streams:

Stream.iterate(0, n -> n + 2)

Stream.generate(Math::random)

Page 50: SoCal Code Camp 2015: An introduction to Java 8

50

CF

Interview Question:

What's the difference between Concurrency and Parallelism?

Page 51: SoCal Code Camp 2015: An introduction to Java 8

51

CF

http://joearms.github.io/2013/04/05/concurrent-and-parallel-programming.html

Page 52: SoCal Code Camp 2015: An introduction to Java 8

52

CF

Interview Question:

What's a Future in Java?

Page 53: SoCal Code Camp 2015: An introduction to Java 8

53

CF

Future models an asynchronous computation and provides a reference to its result that will be available when the computation itself is completed

Page 54: SoCal Code Camp 2015: An introduction to Java 8

54

CF

Future<Double> future = executor.submit(

() -> doSomething());doSomethingElse();

try {Double result =

future.get(1, TimeUnit.SECONDS);} catch (TimeoutException e) {...}

Page 55: SoCal Code Camp 2015: An introduction to Java 8

55

CFpublic Future<Double> getPrice(String product) { CF<Double> f = new CF<>(); new Thread(() -> { try { double price = price(product); f.complete(price); } catch (Exception ex) { f.completeExceptionally(ex); } }).start(); return f;}

Page 56: SoCal Code Camp 2015: An introduction to Java 8

56

CF

public Future<Double> getPrice (String product) { return CF.supplyAsync(() -> price(product))

.exceptionally(() -> 0.0);}

Page 57: SoCal Code Camp 2015: An introduction to Java 8

57

Question

Parallel Streams vs CompletableFutures

Page 58: SoCal Code Camp 2015: An introduction to Java 8

58

CF

Which one to prefer?

Page 59: SoCal Code Camp 2015: An introduction to Java 8

59

CFPattern 1: Async Sequencing

thenAccept*Run a function when complete

thenApply*Convert the result using a function when complete

Page 60: SoCal Code Camp 2015: An introduction to Java 8

60

CFPattern 2: Async Join

thenAcceptBoth* Run a function when both futures are done

thenCombine* Convert the result of 2 futures into a new thing when both are done

Page 61: SoCal Code Camp 2015: An introduction to Java 8

61

CF

CF<String> user = CF.supplyAsync(() ->

"John");CF<String> id =

CF.supplyAsync( () -> "1");

user.thenCombineAsync(id, (u, i) -> u +

i).thenAccept(System.out::println);

Page 62: SoCal Code Camp 2015: An introduction to Java 8

62

References

Java 8 in Action: https://www.manning.com/books/java-8-in-action

@Winterberg: http://winterbe.com/posts/2014/03/16/java-8-tutorial/

IntelliJ for Java Projects

Page 63: SoCal Code Camp 2015: An introduction to Java 8

63

Demo

Page 64: SoCal Code Camp 2015: An introduction to Java 8

64

Demo

Demo 1:• Run code to periodically fetch tweets from Twitter• Store the fetched tweets somewhere

Tech Stack used:• AWS Lambda to create scheduled function• AWS S3 to store fetched tweets• Twitter Streaming Endpoint to fetch tweets

Page 65: SoCal Code Camp 2015: An introduction to Java 8

65

Demo

Demo 2:• Index the stored tweets into an ElasticSearch cluster• Explore and visualize patterns using Kibana Dashboards

Tech Stack used:• AWS Lambda to create a function reacting to S3 events• AWS ElasticSearch Service • Kibana 4

Page 66: SoCal Code Camp 2015: An introduction to Java 8

66

Demo

C03E https://github.com/cganoo/codecamptweetfetcher https://github.com/cganoo/codecamptweetsearcher

The next few slides show screenshots from the demo

Page 67: SoCal Code Camp 2015: An introduction to Java 8

67

Text Search in ES

Page 68: SoCal Code Camp 2015: An introduction to Java 8

68

Summary metrics in ES

Page 69: SoCal Code Camp 2015: An introduction to Java 8

69

Custom Dashboard in ES

Page 70: SoCal Code Camp 2015: An introduction to Java 8

70

AWS Cloudwatch Metrics

Page 71: SoCal Code Camp 2015: An introduction to Java 8

71

AWS Lambda Cloudwatch Logs

Page 72: SoCal Code Camp 2015: An introduction to Java 8

72

Questions?