2014/11/14

Devoxx 2014: Conference day 3 Notes (14/11/2014)


50 new things we can do with Java 8

José Paumard
Date
  • Instant.now()
    • Duration.between(start, end).toMillis()
  • LocalDate.now() — .of() —
    • Period: time between 2 dates
    • now.with(TemporalAdjuster.next(DayOfWeek.SUNDAY));
  • LocalTime.now() — of(10,20) //10:20
  • ZoneTime / ZoneId.of(“Europe/London”)
    • ZonedDateTime — Period
  • Formatter (DateTimeFormatter.ISO_DATE_TIME etc.)
  • Bridge with java.util.Date:
    • Date.from(instant)
    • TimeStamp.from(instant)
    • Date.from / toLocalDate()
Stream
  • IntStream
  • Patter.compile(…).splitAsStream(txt)
String concat
  • compiler does stringbuilder conversion
  • StringJoiner: concat with delimeters + pre-/postfix
    • String.join(…)
Numbers
  • Long.max(), Long.sum()
  • lambda: .reduce(…,Long::max)
  • static Long.hashCode(l)
I/O reading text files
  • Files.lines(Path)
    • path=Paths.get(…);
    • autoclosable with try(resource){} pattern
  • Files.list(path)
  • Files.walk(path): recursive find
Iterable
  • forEach consumes (e.g; strings.forEacht(System.out::println))
  • boolean b = list.removeIf(s-> s.length() > 4)
  • list.replaceAll(String::toUpperCase)
  • list.sort(Comparator.naturalOrder())
Comparator
  • Comparator.naturalOrder()
  • Comparator.comparingBy(Person::getLastName) .thenComparing(Person::getFirstName).thenComparing(..)
  • comparator.reversedOrder() / comp.reversed()
  • Comparator.nullsFirst() /nullsLast()
Optional
  • Optional.empty();
  • Optional.of(“one”)
  • opt.isPresent() /.get() / .orElse(“”) / .orElseThrow()
  • Stream integration ifPresent / filter / map / flatMap
    • flatMap().collect(…)
Map
  • map.forEach( (key, value) -> …)
  • better Compare-And-Swap functions for concurrency:
    • map.get(key) -> map.getOrDefault(key, default)
    • map.putIfAbsent(key, object)
    • map.replace(key, old, new) -> extra test on old value
    • map.remove(key, old) - extra test on old value
    • map.compute() / computeIfAbsent() / computeIfPresent()
Type Annotations
  • @NonNull
Parallel Arrays
  • Arrays.parallelPrefix
  • parallelSort
Completable Future -> graphs of tasks (“reactive programming”)
  • CompletableFuture.supplyAsync()
  • thenApply() thenAccept()
  • thenCompose()
  • allof(): combine multiple futures -> join()
  • thenCombine() / applyToEither: get the first result
Atomic Variables
  • AtomicLong -> updateAndGet(lambda) / accumulateAndGet(lambda)
  • multithreaded ;increment() / .sum() computes final result
StampedLock
  • s.writeLock() s.readLock()
  • tryOptimisticRead()
ConcurrentHashMap
  • completely replaced, no locking
  • size(): do not use! -> map.mappingCount()
  • search(threshold, lambda) : threshold before going parallel
  • reduce() / reduceKey() / reduceEntries()
  • ConcurrentHashMap.newKeySet() // values are Boolean.TRUE
Books
  • Java SE8 for the Really Impatient - Cay Horstman

Introduction to Android Wear - A Glimpse Into the Future

Cyril Mottier
principles:
  • contextual
  • glanceable
  • low interaction

In Full Flow: Java 8 Lambdas in the Stream

Paul Sandoz
Stream Basics
  • Stream:
    • abstract view over data
    • aggregate ops
  • not RxJava, not CompletableFuture, not Distributed Stream
  • e.g.;
    • list.stream().filter(s -> s.length() > 0).count()
    • mapToLong(e -> 1L)
    • reduce(0, Long::sum);
    • reduce(“”, (a, b) -> a + “ “ + b)
    • Optional
  • performance:
    • parallel can go slower for small datasets (due to overhead)
    • reduce can generate a lot of extra classes -> .collect()
Parallel Game
  • a stream is sequential by default
  • can be made parallel()
  • Greedy -> takes more work -> multicore
  • implementation under the hood:
    • forkjoinpool -> split problem in parts
  • when to use?
The future
  • near term:
    • better parallel resource control
    • improved splitting implementations
      • Files.lines()
      • unordered input to limit()
    • more operations:
      • takeWhile()
      • skipWhile()
      • Matcher.stream()
    • helper methods
      • Optional.stream()
      • Stream.ofNullable(T t)
    • longer term:
    • Value types
    • extending generics over values
    • IntStream extends Stream
    • Tuples

2014/11/13

Devoxx 2014: Conference day 2 Notes (13/11/2014)


keynote: Android Material Design

Chet Haase & Nick Butcher
visual design talk :-/

Modern Enterprise Java Architectures with Spring 4.1

Juergen Hoeller
Spring Framework 4.1
  • embedded webserver
  • websocket-style lightweight messaging
  • baseline:
    • min.: java 6, servlet 2.5, JPA 2.0
    • Java 8 support,
  • support:
    • servlet 3.0 oriented
    • compatible with Websphere7 (JPA feature pack)
    • Google App Engine
    • EE7 level:
      • servlet 3.1, Websockets
      • JRSR-236 Managed concurrency
      • JPA2.1, Bean validattion
      • JTA 1.2, JMS 2.0
      • JCache 1.0
    • dedicated support for latest servers
      • Tomcat 8.0, Jetty 9.2
      • GlassFish 4.2, WebLogic 12.1.3
      • Websphere Liberty Profile, WildFly
Spring 4.1 features
  • Component Classes: example meta-data (annotations) (not new)
    • @Service, @Lazy
    • @Autowired
    • @Transactional
  • Configuration classes
    • @Configuration
    • @Profile
  • Composable annotations
    • combine annotations to a “@interface” that groups multiple default annotations
    • overridable annotations: e.g. custom scopes, require specific attributes
  • Generic-based Injection Matching: look for the most specific @Bean match with @Autowired, without qualifiers;
  • ordered collection injection:
    • @Bean @Order(1)
    • @Autowired …List<> is filled with correct beans, using the @Order
  • Lazy Injection Points
  • support for standard annotations: @ManagedBean, @Inject, @PreDestroy -> no need to have spring dependencies
  • java.util.Optional (java 8)
  • Declarative formatting with Java 8 data-time:
    • base: LocalDate, LocalDateTime (java.time.*)
    • @DateTimeFormat(pattern=”M/d/yy h:mm”) (org.springframework.annotations)
    • @Past (javax.validation.constraints.*)
  • Declarative Scheduling
    • @Async
    • @Scheduled (can repeated on a single method)
  • java 8 Lambdas
    • JdbcTemplate, JmsTemplate etc.
  • Annotated MVC Controllers
    • @PathVariable from @RequestMapping(value=”/path/{id}”)
    • @Valid -> bean validation
  • STOMP on WebSocket: @SubscribeMapping
  • Annotated JMS Endpoints:
    • @JmsListener
    • Messaging abstraction: org.springframework.messaging.Message
  • Declarative Caching:
    • use spring’s annotation (not in JEE yet)
      • @CacheConfig
      • @Cacheable
      • @CachePut
      • @CacheEvict
    • or JCache JSR-107 javax.cache.annotations.
      • @CacheDefaults
      • @CacheResult
      • @CachePut
      • @CacheRemove
Demo: start.spring.io

API Design With Java 8 Lambda and Streams

Stuart Marks / Brian Goetz
API: “interface between software pieces” client / library
history:
  • java 5:
    • generics (parameterized types)
    • annotations
  • java 8
    • lambda
    • default methods
    • streams
lambda:
  • pass behavior
    • “functions as data”
    • replaces anon. inner classes
  • subclassing vs functions-as-data
    • “behavioral” patterns: Command, Iterator, Observer/Listener …
    • eg:
      • Collection -> Array -> Streams.toArray(lambda)
      • Iterator -> forEach() (state on stack, one method call)
      • conditional execution (e.g. null elements) -> iilter()
Function composition and High order functions
  • Collections.sort(List, Comparator) -> custom order with Comparator
    • Collectins.sortByType() -> too many specialized methods -> method variation is not the correct solution
    • -> revisit Comparator:
      • higher-order functions to make composing easy
      • Comparator.comparing(keyFunc)
      • Comparator.comparingInt
      • Comparator.thenComparing(): chain comparing
  • Composition / High-order functions are extremely powerful techniques!
    • Java 8 + Lambda’s
    • Strategy / Command patterns
Default Methods
  • interface evolution
  • java 8:
    • enable streams on collections
    • e.g; default remove() implementation on interface
  • reduces pressure to get interface right from the beginning
  • don’t replace abstract classes
    • no private/protected
    • no state
    • client vs subclasser interface distinction is difficult
Static methods on interfaces
  • less need for utility classes (e.g. Collections)
  • static factory methods: Comparator.comparing()
Streams in APIs
  • aggregations of other things:
    • historically: Collection
      • defensive copy
      • performance issues
    • java8: Stream
      • lazy by default
      • avoid making defensive copies
      • no need for conversion
      • can be infinite
      • (use Collection is repeatable read is required)
      • client can filter(), collect(), findFirst() on Stream
Optional
  • wrapperclass: value is present or empty
  • consider when a method can return null
  • reducess NullPointerExceptions
  • usages: min/max on empty input; find/search
  • orElse(), orElseThrow()
Generics
  • type inference relies on generics
  • raw types give issues
  • use wildcards :-/
others:
  • deprecate/remove old stuff? “removing has almost only drawbacks”

Don’t be naked in front of JavaScript: 15 essential tools explained in 15 minutes

Romain Linsolas
  • books:
    • Javascript the good parts
    • Javascript definitive guide
  • NodeJS:
    • serverside; npm
    • Express: REST
  • Yoeman: scafold project
    • yo angular
  • Bower: dependency mgmt
  • Grunt: task runner
    • config over code
    • ant for javascript
  • Gulp: Stream-besed build system
    • code over config
  • IntelliJ/ WebStorm
  • Jasmine: unit tests and functional tests
  • CasperJS: integration testing
  • Google Closure Compiler
  • SonarQube:
    • coding rules
    • test coverage
  • Batarang: Chrome extension
    • Angular debugging / profiling
    • inspect scopes
    • watch perf.

Java 8, 9 and beyond - Ask the Experts

Brian Goetz / Paul Sandoz / Stuart Marks
  • reified generics instead of erased genics: dificult with wildcards / complex within compiler -> address painpoints
    • better type literals
    • arrays: immutable
    • arraylist of int
  • jdk 9
  • parallelstreams by default -> start sequential, measure
  • backwards compatibility: burden? -> “constraint”
  • checked exceptions: failed? part of the platform.
    • difficult with generics

3D Printing, Teaching Java & Visual Programming

Michael Hoffer
3D Printing: plastic: layers of material ‘additive’ -prototyping (industry: remove layers)
How to create 3D geometries?
  • professional CAD
  • Blender (free) -> design
  • OpenSCAD
  • JCSG / JFXScad (Java libraries)
    • Union, Diff, Intersection or Hull
VRL-Studio
  • General purpose visual programming language
  • Automatic GUI gen
  • jar-file
  • JCSG Plugin -> 3d drawing
    • save as STL file -> to printing software

Pragmatic Functional Refactoring with Java 8

Raoul-Gabriel Urma / Richard Warburton
First-class Functions
  • classic: interface Predicate / implemented
  • java 8:
    • method refs: this::myMethod()
    • lambdas
  • composing functions
    • java.util.function.Predicate -> test()
      • has default methods e.g; or(), and() etc.
    • function pipelines: java.util.function.Function
      • andThen() chaining
Currying
  • DoubleUnaryOperator class
  • partial application: using some arguments and returning a new function
Immutability
  • withXxxxx() methods instead of setters that copy the object and return the modified version
  • copy objects to prevent racecondition issues with internal state
  • related
    • domain driven design: immutable value types
    • tools:
      • JSR-308: annotations
      • Mutability Detector
      • FindBugs @Immutable test
Optional Data Types
  • NullPointerException protection
  • java.util.Optional
    • single value container
    • excplicit modelling
    • must be actively unwrapped
    • construct: Optional.ofNullable(person);
    • Optional.flatMap(Person::getCar — can be chained -> return Optional value
Books:
  • Java 8 in Action
  • Java 8 Lambdas

Evening Keynote: Infinite Possibilities

Denise Jacobs
  • creativity
  • fixed (perfectionism) or growth mindset?
  • ‘release tirany of the expert’
  • adopt a beginner’s mind
  • “flow”
  • make bug lists
  • choose bigger/creative problems to solve
  • ‘culture of creativity’

2014/11/12

Devoxx 2014: Conference day 1 Notes (12/11/2014)

keynote

jboss

  • containers
  • microservices
  • “Camel”

oracle

  • 20 years java (1995)
  • java 8 Brian Goetz
    • lamba’s
    • stream() / parallelStream() (List / Hashset api)
    • default methods
  • next
    • —> jigsaw module system
      • small devices (compact profile)
      • security mechs
      • startup performance
      • blocked usage of sun*internal stuff
      • part of openjdk
    • Poject Valhalla
      • cache misses / align curren tmemory
      • sepcialized generics
      • value types
      • var handles
    • Project Panama
  • IoT Jasper Potters

Devoxx 2014: Pico Services with Java EE 7 on Java 8 and Docker

Adam Bien
base concepts:
  • JAX-RS
  • @Inject
  • Business component: Boundary Control Entity pattern
setup demo
  • netbeans
  • glassfish v4
  • simple pom.xml: javax / javaee-api 7.0
  • JAX-RS
  • @Stateless EJB (bean.xml in JEE6)
  • docker:
    • test environment
    • expose ports
    • jenkins in docker
    • “ambassador pattern” -> used for real data

60 useful Linux commands in 15 minutes

Pierre-Antoine Grégoire

Sparky guide to bug-free JavaScript

Mite Mitreski
  • debugger; statement: force debugger
  • console.table clean format in console
  • console.trace + Objects.observe who changed object?
  • async debug (full stactrace) async
  • DOM mutation Observer
  • log with google analytics gaq.push() :-/

Let’s Get Physical: I/O Programming with Java on the Raspberry Pi using Pi4J

Robert Savage
  • Pi4j:
    • open source / Low level IO
    • event based
    • java + JNI (C)
  • IO interfaces
    • digital interfaceGPIO/ PWM
    • data UART, serial, SPI, I²C
    • analog interfaces: extra hardware
  • models
    • a/b: 21 GPIO
    • b+ 28 GPIO
    • compute module: 46

Spotify - audio delivery at scale

Niklas Gustavsson
  • commoditiy servers
    • high availibility, robustnest
    • colocated
  • backend services
    • ‘atomic’
    • self-executing jar
    • wired toghether with propriatary protocol (zeromq-based)
  • clients: keep socket open
  • Service Discovery: DNS records
  • robustnest / scalability:
    • storage: Cassandra
  • teams
    • autonomuous org.
    • general principles / rules (programming language etc.)
  • content distribution
    • attempt to do local caching (depends on device)
    • “storage resolve” service -> file location
    • CDN’s
      • audio-files are not really ‘standard’ content for CDN’s
      • multiple providers
      • performance is correlated with amount of data served from CDN
  • measure!
    • latency
    • buffering
  • others:
    • no p2p
    • only desktop clients (battery / bandwidth constraints)
    • prefetching
    • head files: first few seconds (unencrypted on CDN)

Concurrency in Enterprise Java

Alexander Heusingfeld
Java SE 5 classic Thread -> java.util.concurrent
  • ExecutorServices
  • no trx’s
  • etc.
patterns of software stability
  • timeouts
  • bulkheads: separate app components
  • curcuit breaker: failfast on thread starvation
  • steady state: free unused resources
JSR 236: javax.enterprise.concurrent
  • containermanaged threads
  • ManagedThreadFactory
    • extends ThreadFactory from SE
    • ManageableThread
    • use ExecutorServices from SE
    • fork/join pool not supported
  • ManagedExecutorService
    • jndi lookup
    • lifecycle api’s disabled
    • List >executor.invokeAll()
  • ManagedScheduledExecutorService
    • schedule tasks with trigger (e.g. executor.scheduleAtFixedRate())
  • ContextService
  • ManagedTaskListener -> event management
    • ManagedExecutors class
runtime remarks:
  • wildfly (JBoss): special commanline options
  • some gotcha’s as this is new technology
    • check RejectionPolicy
    • Java 8 Streams API (parallelStream -> uses ForkJoinPool internally, not compatible with ManagedThreads)
  • running on < Java8: Guava — ListeningExecutorService -> Callbacks
  • Netflix Hystrix: stability patterns (e.g. Circuit-Breaker)
    • custom threadpool
    • hystrix.plugin.HystrixConcurrencyStrategy
Summary JSR 236:

Predictability and Performance

Richard Warburton
“be predictable”
Branch prediction:
  • cpu-cycles: fetch, decode, exec, writeback
  • branch -> stall -> predict
    • static: no dynamic data considered
      • forward: not taken
      • backware: taken
    • local / global
    • performance event counters:
      • specific registers -> can store prediction info
  • demo time perf java ...
Locality
  • arrays -> strides
  • good data layout principles
    • primitive collections: HPPC, FastUtil, GNU Trove)
    • arrays instead of linked lists
    • hashtable instead of tree
    • custom data-structures: judy arrays, kD-Trees, Z-Order Curves
  • java heap layout issues: no location guarantee (GC etc)
    • off heap structures (libraries)
Storage
  • seeking vs sequential reads
  • fragmentation: preallocate
  • sector misalignment: offset logical vs physical sector
  • iotop

The end of traditional enterprise IT

Ron Van Kemenade (CIO ING group)