Slides of my talk as Devoxx 2015. How to set up asynchronous data processing pipelines using the CompletionStage / CompletableFuture API, including how to control threads and how to handle exceptions.
Common issues with Apache Kafka® Producerconfluent
Badai Aqrandista, Confluent, Senior Technical Support Engineer
This session will be about a common issue in the Kafka Producer: producer batch expiry. We will be discussing the Kafka Producer internals, its common causes, such as a slow network or small batching, and how to overcome them. We will also be sharing some examples along the way!
https://www.meetup.com/apache-kafka-sydney/events/279651982/
Traditional approaches to integration testing—using shared, local, or in-memory databases—fall short for today's modern developer.
Developers today are building cloud native distributed microservices and are taking advantage of a rich variety of backing services. This explosion of applications and backing services introduces new challenges in creating the necessary environments for integration testing. To be useful and effective, these environments must be easy to create and they must resemble production as closely as possible. New solutions are needed to make this need a reality.
Enter Testcontainers!
Testcontainers Java is a library that supports JUnit tests and makes it incredibly easy to create lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.
In this talk, you'll learn when and how to use Testcontainers for Java. We'll cover the fundamentals and walk through examples to illustrate various ways you can apply Testcontainers to your applications.
En attendant la publication de Java 21, la prochaine version diffusée en septembre de cette année, et pour en donner quelques aperçus, cette présentation brosse une revue détaillée des nouveautés qui devraient être proposées dans cette future version LTS de Java, issues des projets Amber, Loom et Panama d’OpenJDK.
NGRX provides tools for implementing Redux patterns in Angular applications. The key components are:
- The Store holds the single source of truth application state as plain JavaScript objects and uses reducers to immutable update state in response to actions.
- Actions describe state changes and are dispatched to the Store which passes them to reducers. Reducers pure functions that return new state.
- Selectors allow slices of state to be accessed.
- Additional libraries provide debugging with devtools, routing integration, side effect handling, and entity management functionality. Files can be organized by domain or feature module.
Unique ID generation in distributed systemsDave Gardner
The document discusses different strategies for generating unique IDs in a distributed system. It covers using auto-incrementing numeric IDs in MySQL, which are not resilient, and various solutions like UUIDs, Twitter Snowflake IDs, and Flickr ticket servers that generate IDs in a distributed and ordered way without coordination between data centers. It also provides code examples of generating Twitter Snowflake-like IDs in PHP without coordination using ZeroMQ.
The aggregate is dead! Long live the aggregate! - SpringIO.pdfSara Pellegrini
https://2023.springio.net/sessions/the-aggregate-is-dead-long-live-the-aggregate/
SARA PELLEGRINI - AXONIQ
MILAN SAVIC - AXONIQ
DDD’s definition of Aggregate may seem somewhat confusing - “An aggregate is a cluster of associated objects that we treat as a unit for the purpose of data changes.” Okay, let’s try to clarify - “You should consider your aggregate as a unit of consistency in your Domain.”. That doesn’t help either. As a matter of fact, while modeling our systems, we tend to group together events related to the same domain concept; we tend to define groups based on the nouns we find inside our events’ name: saying “this is our aggregate!”. According to the aggregate definition, we should instead ignore these nouns, and put together the data that change together. Easier said than done: in the modeling phase it is easy to make mistakes trying to identify the boundaries of our aggregates based on this rule. If we opt for saving the state of our aggregate as a series of events, we are in big trouble - any (serious) refactoring of the aggregate structure becomes close to impossible. The reason for this trouble is that we have to make a decision in the design phase for which we cannot be lenient. We are basically married to this decision forever. Due to the aforementioned reasons (and many others), people struggle with the Aggregate pattern. Some even say it is unnecessary, we are one of those. Let’s see whether we can model our business constraints without aggregates. Could we be more relaxed when consistency is in question? Join us to discover how!
The document discusses Redux Toolkit, a framework for building Redux applications. It introduces key Redux concepts like actions, reducers, and middleware. It explains how Redux Toolkit simplifies Redux setup with utilities like thunk and Immer.js. It demonstrates Redux Toolkit APIs like configureStore, createAction, createReducer, and createSlice that generate action creators and reducer logic to update state in response to actions.
React Hooks were introduced in React 16.8 to add state and side effects to function components by replacing class components. Common hooks include useState for managing component state, useEffect for handling side effects like data fetching, useCallback for creating memoized functions, and useRef for creating references that don't trigger re-renders when mutated. Hooks allow extracting logic into custom reusable hooks and following a few simple rules helps avoid bugs.
Spring Boot is a framework for creating stand-alone, production-grade Spring based applications that can be "just run". It aims to provide a radically faster and widely accessible starting experience for developing Spring applications. Spring Boot applications can be started using java -jar or traditional WAR deployments and require very little Spring configuration. The document then discusses system requirements, development environment, creating a simple Hello World application, using Spring Boot Admin to monitor applications, configuring databases, Spring Data JPA, REST controllers, caching with EhCache, building web applications with Thymeleaf, and project structure.
Introduction to Spring WebFlux #jsug #sf_a1Toshiaki Maki
The document provides an introduction and overview of Spring WebFlux, a non-blocking web framework for Spring. It discusses the differences between blocking and non-blocking web stacks, and how Spring WebFlux uses reactive streams and programming. Code examples are provided showing how to build reactive controllers and streams in Spring WebFlux that support backpressure.
50 nouvelles choses que l'on peut faire avec Java 8José Paumard
Java 8, c'est bien sûr l'arrivée des lambdas, des Stream et des Collectors. Mais ce n'est pas que cela. Plein de nouvelles choses sont aussi offertes : un nouvelle API pour les dates, un nouveau moteur Javascript, une nouvelle version de JavaFX, une nouvelle ConcurrentHashMap, une nouvelle HashMap, des nouveautés dans le domaine de la concurrence, et toutes sortes de petites choses qui vont nous faciliter la vie, que l'on se propose de passer en revue ici.
Communication between Microservices is inherently unreliable. These integration points may produce cascading failures, slow responses, service outages. We will walk through stability patterns like timeouts, circuit breaker, bulkheads and discuss how they improve stability of Microservices.
The java persistence API provides a specification for persisting, reading, and managing data from your java object to your relational tables in the database. JPA specifies the set of rules and guidelines for developing interfaces that follow standards.
The document discusses hexagonal architecture, also known as ports and adapters architecture. It is an alternative to traditional multi-layer architectures that aims to decouple the application core from external influences like databases, web frameworks, and other dependencies. The core domain logic is separated from external influences by defining application programming interfaces (APIs) called "ports" that external "adapters" implement. This allows the core to be developed and tested in isolation. The document provides an example implementation of a ticket management system using this architecture.
Whitebox testing of Spring Boot applicationsYura Nosenko
This document discusses whitebox testing of Spring Boot applications. It begins with introductions and backgrounds, then discusses issues with existing testing frameworks like TestNG and JUnit 4. It proposes alternatives like Spock and JUnit 5, highlighting advantages of each. It also provides an overview of Spring Boot testing capabilities, focusing on integration testing support, transaction handling, main components, and reactive support. It concludes with examples of setting up Spring Boot testing with Spock and JUnit 5.
The session will provide the knowledge about react page life cycle and how more precise actions or operations can be performed using react hooks concepts
Functional Patterns with Java8 @Bucharest Java User GroupVictor Rentea
The slides for the presentation I gave at Bucharest Java User Group. This session was the largest Romanian Java community meetup ever organized until now.
CQRS and Event Sourcing, An Alternative Architecture for DDDDennis Doomen
Most of us will be familiar with the standard 3- or 4-layer architecture you often see in larger enterprise systems. Some are already practicing Domain Driven Design and work together with the business to clarify the domain concepts. Perhaps you’ve noticed that is difficult to get the intention of the 'verbs' from that domain into this standard architecture. If performance is an important requirement as well, then you might have discovered that an Object-Relational Mapper and a relational database are not always the best solution.
One of the main reasons for this is the fact that the interests of a consistent domain that takes into account the many business rules, and those of data reporting and presentation are conflicting. That’s why Betrand Meyer introduced the Command Query Separation principle.
An architecture based on this principle combined with the Event Sourcing concept provides the ideal architecture for building high-performance systems designed using DDD. Well-known bloggers like Udi Dahan and Greg Young have already spent quite a lot of of posts on this, and this year’s Developer Days had some coverage as well.
But how do you build such a system with the. NET framework? Is it really as complex as some claim, or is just different work?
The document discusses CompletableFuture in Java. It begins with an introduction to java.util.Future and its limitations. It then discusses how CompletableFuture allows asynchronous and parallel operations through callbacks and chaining of tasks. This improves performance over serial execution. It provides examples of CompletableFuture methods like supplyAsync, thenApply, thenCombine, and allOf. Finally, it discusses how CompletableFuture can be used to build powerful and scalable libraries.
The document discusses building an orchestration layer for a travel agency service using JAX-RS 2.0 and Jersey 2. It describes a naive synchronous approach that makes sequential requests slowing performance, and proposes an optimized asynchronous approach using asynchronous requests to improve performance by processing requests concurrently instead of sequentially. It provides examples of synchronous and asynchronous client code to call external services.
The document introduces CompletableFuture in Java, which is a library that allows asynchronous and non-blocking operations to be performed and chained together. It provides methods to chain dependent tasks together without blocking or callback hell. CompletableFuture implements Future and CompletionStage interfaces and provides various methods to handle results, errors, chaining and composition of asynchronous operations.
This Presentation presents how Data science can bring manifold benefits to Retail Broking. Machine Learning & Text Analytics can impact your business in many positive ways- gives you that competitive edge and gains you customer satisfaction & loyalty
First appeal under RTI Act 2005 against Registrar (J-I) Supreme Court of Indi...Om Prakash Poddar
First appeal under RTI Act 2005 against Registrar (J-I) Supreme Court of India for REFUSAL OF REGISTRATION OF WRIT CRIMINAL AGAINST UNION OF INDIA D.NO.2188 OF 2017
Aggrieved by the reply of Adl. Registrar & CPIO, Supreme Court of India dated 04.03.2017, appellant preferred First Appeal against CPIO of Supreme Court of India dated 07.03.2017 before Ld. Registrar (Admin) & First Appellate Authority (FAA) Supreme Court of India at New Delhi.
This document discusses optimizing designer pages on a fashion e-commerce site. It notes that designer names are among the top search terms and that designer pages are the highest value page type to engage new visitors. It recommends focusing on improving designer pages to enhance the user experience on mobile by reducing load times, which can negatively impact conversions and engagement. It then provides details on how site furniture and listing pages were implemented using various technologies like Webpack loaders and APIs.
Transformation structurelle et émergence au Sénégal - Madaniou DIEMEMadaniou DIEME
Dans un contexte marqué par la vision d’un Sénégal émergent (émergence économique) et la lutte contre la pauvreté (émergence sociale), l’étude sur la transformation structurelle pour l’émergence du Sénégal, trouve toute sa justification empirique et toute son actualité.
There are a lot of great things about the cloud, but the "destroy and rebuild" philosophy which is really good for building a continuous delivery pipeline, really sucks when applied to troubleshooting production problems. When your application goes haywire, the most valuable engineering skill is not the the ability to bring up a copy of your system or even the knowledge of your technology stack (although it doesn't hurt). It is the skill of understanding and solving problems.
Finding the root cause of the issue and mitigating it with minimal disruption in production is a must-have skill for engineers responsible for managing and maintaining production systems, which nowadays includes ops, dbas and devs alike. In this talk I will discuss the skills required to troubleshoot complex systems, traits that prevent engineers from being successful at troubleshooting and discuss some techniques and tips and trick for troubleshooting complex systems in production.
The document discusses Java 8 streams and reactive programming. It covers:
1) An overview of Java 8 streams, including how they are implemented using spliterators and pipelines and do not store data;
2) Common patterns for creating and using streams to map, filter, and reduce data;
3) How stream characteristics are used for optimizations;
4) How spliterators can be overridden to support non-standard data sources and enable operations like grouping and rolling streams.
DevOpsDays Baltimore March 2017 - Continuous Integration: A bittersweet love ...Suzie Prince
This is the bittersweet story of Continuous Integration. CI is practice that we fell in love with, embraced and then never fully committed to. I’ll share with you the current state of CI, what we think we are doing when we say CI and what we are really doing in terms of CI. Then I’ll remind us all why we fell in love with CI in the first place and make some suggestions on how to get back to the good stuff.
Updated for 2017. Presented at DevOpsDays Baltimore 2017.
The document discusses various policies that governments can implement to protect the environment, including taxes, subsidies, laws, and regulations. It provides definitions for each: environmental taxes increase the cost of polluting goods, subsidies make green goods cheaper, laws ban harmful products, and regulations impose rules to reduce pollution. The document aims to help students understand these policy options and how governments use them to encourage sustainable growth while protecting the environment. It provides examples of these policies in practice and discusses their potential impacts and effectiveness.
Java 8, Streams & Collectors, patterns, performances and parallelizationJosé Paumard
This document discusses Java 8 streams and collectors. It provides an overview of streams, operations on streams like forEach(), filter(), and peek(), and functional interfaces like Consumer and Predicate. It notes that streams efficiently process data in a parallel and pipelined manner without storing intermediate data. Key points covered include what streams are, how to create them from collections, common stream operations, and issues around concurrency with mutable operations.
This document discusses monitoring Apache Kafka clusters and applications with Prometheus. It provides an overview of the architecture used, including deploying Prometheus servers, Kafka and HBase exporters, and a JSON exporter for YARN applications. Specific exporters are discussed for Kafka brokers using JMX, Kafka clients using the Prometheus Java library, and exposing application metrics via HTTP. Important Prometheus configurations and query functions are also covered. The summary highlights the key components of the monitoring architecture and some of the exporters and techniques discussed.
Containerd - core container runtime component Docker, Inc.
Docker extracted its core container runtime component called containerd and donated it to an open source community project to accelerate innovation across the ecosystem. Containerd provides the core primitives to manage containers on Linux and Windows hosts and will be fully compliant with the Open Container Initiative standard. Major container platforms like Docker will use containerd as their core runtime component to provide a "boring" infrastructure component and allow for greater cross-platform compatibility and collaboration.
The document provides information on handling API requests in Android using AsyncTask. It discusses the different ways to handle API in Android including AsyncTask, Volley, and Retrofit. It then focuses specifically on AsyncTask, explaining what it is, its generic types, methods like doInBackground(), onPreExecute(), onPostExecute(), onProgressUpdate(). It outlines the execution steps of an AsyncTask and provides an example of handling API requests using AsyncTask to fetch contact data from a URL. The example discusses adding internet permission, creating an HTTPHandler class to make the request, parsing the JSON response using model classes, and displaying the data in a recycler view.
Leveraging Completable Futures to handle your query results AsynchrhonouslyDavid Gómez García
The document discusses leveraging CompletableFutures to handle asynchronous query results in Java. It begins with an overview of concurrency vs parallelism and tools in Java for concurrency. It then covers using ExecutorServices and Futures to run tasks asynchronously before introducing CompletableFutures, which allow fluent chaining and composition of dependent asynchronous tasks. Examples are provided of using CompletableFutures to run database queries asynchronously and maximize performance. Considerations for using CompletableFutures in APIs are also discussed.
The document discusses Node.js, which is a server-side JavaScript environment that uses an asynchronous event-driven model. Some key points:
- Node.js uses the V8 JavaScript engine and allows handling requests via JavaScript on the server-side rather than a separate language like PHP, Java, etc.
- It has non-blocking I/O to avoid blocking the entire process when waiting for slow resources like files or databases. Callbacks are used to handle asynchronous operations.
- The document discusses how Node.js could provide access to MUMPS databases to take advantage of the benefits of global storage while using the popular JavaScript language.
Leverage CompletableFutures to handle async queries. DevNexus 2022David Gómez García
Slides used at DevNexus 22 talk.
Completable futures were introduced in Java 8, and they are a powerful mechanism to add concurrency (not parallelism) to your application logic, and it may be handy when dealing with multiple queries to different systems.
If you are a developer, you may make your code more performant by using CompletableFutures where it makes sense.
If you are a library developer, it may be a good thing to offer an API that returns CompletableFutures so that your users will be able to benefit from it.
The document discusses asynchronous programming and different approaches to handling asynchronous operations. It covers asynchronous programming concepts like asynchronous functions, asynchronous callbacks, and asynchronous events. It then describes different asynchronous programming models including synchronous, asynchronous programming model (APM), event-based asynchronous pattern (EAP), task-based asynchronous pattern (TAP), and async/await. Code examples are provided to illustrate each approach.
The document provides an overview of Node.js and the Express web framework. It discusses that Node.js is a platform for executing JavaScript files and includes utilities for network and file I/O. Express is a web application framework built on Node.js that uses middleware to handle requests. The document covers Express concepts like routing, middleware, templating, and popular middleware modules for tasks like compression, parsing request bodies, and sessions.
Functional Programming is preferred since it uses pure functions and values and keeps side effects at bay. However, while building real-life applications, side effects are often needed in the scenario when, say, one needs to query a database or read from or write to the stream.
If you’re facing this challenge in your projects too, then IO Monads can come to your rescue. Explore how using IO Monads, Scala developers can smoothly encapsulate side effects and write graceful programs while maintaining purity in Functional programming.
1. How to deal with side-effects in Scala in a purely functional way?
2. Important features like
a) Synchronous and asynchronous computations
b) Error handling
c) Concurrency
d) Parallelism
e) Cancellation
The document discusses asynchronous programming in .NET 4.5 using tasks and async/await. Key points include:
- Tasks and Task<T> represent asynchronous operations and let you specify continuations using ContinueWith.
- The async modifier indicates an asynchronous method, which returns a task. Await pauses execution until the awaited task completes.
- Async methods make long-running work non-blocking. The caller resumes without waiting for the async method to finish.
- Async and await simplify asynchronous code by turning callbacks into synchronous-looking code.
Java 8 Puzzlers as it was presented at Codemash 2017Baruch Sadogursky
We aren’t sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven’t reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well. Baruch and Viktor will show you some surprising, bizarre, and inconceivable parts of Java 8 and make sure that you won’t be (too) surprised when it hits you in production. As with any other puzzlers talk, there will be two speakers, lots of puzzling questions, answers by the audience, T-shirts flying around, and a lot of fun, all for one purpose—to help you better understand Java 8.
Writing a REST Interconnection Library in SwiftPablo Villar
The document summarizes Pablo Luciano Villar's presentation on writing a REST interconnection library in Swift. The presentation covered the motivation for such a library, proposed an architectural concept using repositories and backends to abstract network calls, and provided an implementation example in Swift using protocols, generics, enums, and other features. Key aspects included defining a common API for CRUD operations across different entities, handling asynchronous network requests with Futures, and enhancing error handling and data parsing. The full implementation is available as an open source library called Jayme.
Java APIs- The missing manual (concurrency)Hendrik Ebbers
This isn’t a talk about microservices, NoSQL, container solutions or hip new frameworks. This talk will show some of the standard Java APIs that are part of Java since version 5, 6, 7 or 8. All those features are very helpful to create maintainable and future-proof applications, regardless of whether JavaEE, Spring, JavaFX or any other framework is used. The talk will give an overview of some important standard concepts and APIs of Java like annotations, null values and concurrency.
This document provides an overview of the Play! web framework for Java, including how it differs from traditional Java web development approaches by avoiding servlets, portlets, XML, EJBs, JSPs, and other technologies. It demonstrates creating a simple PDF generation application using Play!, including defining a model, controller, and view. The framework uses conventions over configuration and allows rapid development through features like automatic reloading of code changes and helpful error pages.
Ultimate Node.js countdown: the coolest Application Express examplesAlan Arentsen
Node.js is hot and that's not without a reason. There are numerous examples of large websites using Node.js and there is some pretty cool stuff out there.
Since Application Express is officially 'Awesome' and Node.js is 'hot', why not combine the two? With node-oracledb and websockets you can do awesome things, but there is more Node.js has to offer!
In this presentation you will get a short introduction on Node.js. After that I will show you a handful of Node.js applications in Application Express sorted on awesomeness from cool to sub zero.
Santiago Pericas-Geertsen presented on new features in JAX-RS 2.1 including reactive extensions, server-sent events, and non-blocking I/O. He demonstrated the new reactive client API using CompletionStage and how it can compose asynchronous requests. He also showed how to implement server-sent events on the client and server side to enable one-way messaging. Finally, he proposed a new approach to non-blocking I/O in JAX-RS based on Java 9 Flows to allow processing collections of POJOs asynchronously.
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
This document provides an introduction and overview of RxJava. Some key points:
- RxJava is a library for composing asynchronous and event-based programs using observable sequences. It implements Reactive Extensions (ReactiveX) for the Java VM.
- Using RxJava can help address issues with concurrency, callbacks, and composing asynchronous operations in Java. It promotes a reactive style of programming.
- The core abstractions in RxJava are Observables (which emit notifications), Subscribers (which receive notifications), and Operators (which allow transformation and manipulation of observable sequences).
- Examples are provided of how to use RxJava with Clean Architecture, including reactive presenters, use cases that
This document discusses asynchronous programming in C# using the Async CTP. It explains why asynchronous programming is important for responsive user interfaces and scalable services. It demonstrates how to convert synchronous code to asynchronous using the new async and await keywords in C#, while maintaining a natural code flow. Key aspects of the Task-Based Asynchronous Pattern are outlined, including error handling and progress reporting. The document provides resources for learning more about asynchronous programming in C# and the implementation details of the Async CTP.
어느덧 스무살이 된 자바. 좋든싫든 프로그래밍의 세계에 몸담고 있는 이상 부딪히지 않을 수 없는 언어인데요, 이 자바에 대한 올바른 모습의 이해화 앞으로 나아가야 할 방향을 모색해본다는 의미에서 "모던 자바의 역습"이라는 타이틀로 실시한 온라인 세미나의 슬라이드 자료입니다.
진행자: 김대우(http://lekdw.blogspot.kr/)
정도현(http://moreagile.net)
이번 세미나는 게임개발자이신 김대우님을 모시고 진행하게 되었는데요 자바 언어와 관련 하여 다음과 같은 주제로 두시간에 걸쳐 발표를 진행합니다.
- 간단히 살펴보는 자바20년의 발자취
- 자바를 둘러싼 진실 혹은 거짓(성능,생산성,품질)
- SI영역 이외에서 자바의 가치
- 모던자바의 역습: 자바8과 함수형 프로그래밍
- 자바 개발의 새로운 패러다임들
This document discusses using async and await in Dart for asynchronous programming. It explains that async and await allow Dart functions to interact with asynchronous operations by suspending function execution to wait for an asynchronous task to complete. An example demonstrates defining an async function that uses await to call another asynchronous function and wait for its future value before returning. Key terms defined include async, async function, await, and future.
Concurrency and Thread-Safe Data Processing in Background TasksWO Community
This document discusses running long-running tasks asynchronously in background threads in Java and WebObjects. It covers:
- Using Runnable and Callable interfaces to define asynchronous tasks
- Executing tasks using the ExecutorService interface and submitting tasks to get Future objects
- The ERXExecutorService class, which provides a thread-safe ExecutorService for WebObjects
- Monitoring and controlling tasks using interfaces like ERXStatusInterface
- Passing EOF objects between threads safely using global IDs
- Customizing the results page using IERXPerformWOActionForResult
Similar to Asynchronous API in Java8, how to use CompletableFuture (20)
The Loom project has been under work for many years, and just delivered Virtual Threads as a preview feature in the JDK 19. We now have a very precise idea of what they are and what you can do with them. Our good old Threads, created more than 25 years ago, will see a new kind of lightweight threads. This presentation shows you that creating a thread is easier and much cheaper, allowing the creation of millions of them in a single JVM. These virtual threads can be block at almost no cost. These new virtual threads bring with them new notions that will be covered in this talk. Loom threads are coming, and they will change the landscape of concurrent programming in Java.
The features released between Java 11 and Java 17 have brought a greater opportunity for developers to improve application development productivity as well and code expressiveness and readability. In this deep-dive session, you will discover all the recent Project Amber features added to the Java language such as Text blocks, Records (including Records serialization), Pattern Matching for instanceof, switch expression, sealed classes, and pattern matching for switch. The main goal of the Amber Project is to bring Pattern Matching to the Java platform, which will impact both the language and the JDK APIs. You will discover record patterns, array patterns, as well as deconstruction patterns, through constructors, factory methods, and deconstructors.
The Future of Java: Records, Sealed Classes and Pattern MatchingJosé Paumard
The release of the JDK 17 brings interesting features in the Java language: sealed types and pattern matching for switch. Along with the introduction of records, the implementation of pattern matching in the Java language begins to take shape. This presentation shows you how records, sealed types, and pattern matching can change the way we write Java code, on real patterns. It also shows you what we can expect to see on this topic in the future. It is mostly a live coding presentation, with some slides when the code is shown cannot be executed.
Designing functional and fluent API: application to some GoF patternsJosé Paumard
These are the slides of my Devnexus 2020 talk. The code is avaiblable on my GitHub account: https://github.com/JosePaumard/devnexus-2020-visitor-lambda. You can see a replay of this talk (in a slightly different version) here: https://youtu.be/gq23w9nycBs
Those are the slides of the presentation we made with Maurice Naftalin à Goto: Copenhagen 2019.
Functional programmers have been saying for decades that they know the way to the future. Clearly they've been wrong, since imperative languages are still far more popular. Clearly they've also been right, as the advantages of functional programming have become increasingly obvious. Is it possible to combine the two models? Scala is one language that does this, and Java too has been on a journey, which still continues, of learning from functional languages and carefully adding features from them. In this talk, we'll review what Java has learned from functional languages, what it can still learn, and how its added features compare to Scala's original ones.
The document discusses the evolution of functional programming features in Java and Scala over time. It notes that Scala was able to adopt features like generics, higher-order functions, and pattern matching earlier than Java due to not having backwards compatibility constraints. Java gradually added these features in pieces (generics in 2004, higher-order functions in 2014, pattern matching is upcoming) while Scala incorporated them as a whole when it launched in 2004. The document also examines some of the challenges Java faced in implementing these features due to its type erasure approach to generics and desire to maintain backwards compatibility.
Designing functional and fluent API: example of the Visitor PatternJosé Paumard
This is the slide deck of my talk from Devoxx Belgium 2019. You can watch the video here https://www.youtube.com/watch?v=gq23w9nycBs and get the code here: https://github.com/JosePaumard/devoxx-belgium-2019-visitor-lambda.
Among the patterns from the GoF, the Visitor is probably the more complex to implement. One of the difficulties is that you need to implement it in your object model, leading to complex refactoring for legacy applications. Based on the use of all the nifty tools brought by functional programming: chaining, composition, and partial application, you can implement Visitors without having to change your object model, using a functional and fluent API. This approach can be used to implement other patterns: Builder and Validator. Using this way of designing API leads to readable and robust code, designed following the GoF patterns.
Les slides du Tools in Action que j'ai donné à Devoxx France 2019.
Le JDK est open source et son développement aussi. L'ensemble des nouveautés vit sur des branches Mercurial qui peuvent être téléchargées et compilées à la demande. Cela permet de jouer avec des fonctionnalités encore en chantier, de regarder comment les nouvelles syntaxes fonctionneront, bref, de jouer avec un JDK du futur, qui n'existera peut-être jamais. L'objet de ce tools in action est simple : montrer comment tout ceci fonctionne, de l'installation d'une machine Ubuntu à l'exécution d'un JDK recompilé maison.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Lambda and Stream Master class - part 1José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This first part covers Lambda Expressions and API design with functional interfaces.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Slides of the talk we gave with David Delabassee at Oracle Code One 2018.
The FnProject was released about a year ago, proposing new ways to design asynchronous systems in a very flexible way. This tutorial shows you how to set up a Fn Server on a local development machine running Windows with a first simple function. Then we cover the design of multi-functions systems, connected together in an asynchronous way, leveraging the Fn Flow API. This API is first presented, including how it compares to the the Java 8 CompletableFuture API. We then set up a real example made of several functions, producing multiple results and see how we can leverage their asynchronous nature to make a non-blocking system, handling errors in a simple and intuitive way. Most of the examples are shown both on slides and live coding parts.
Avec la version 9 sortie en septembre 2017, Java appuie sur la pédale ! Le rythme des livraisons passe à une version majeure tous les 6 mois. Java 10 est sorti en mars, prochaine version en septembre. Java 10 apporte le 'var' et l'inférence de type pour les variables locales. D'autres nouveautés sont en préparation : les constantes dynamiques, les classes de données, un nouveau switch à base de lambda, des interfaces fermées, de nouvelles choses du coté des génériques et bien plus encore.
Cela viendra-t-il en 11, 12, 15 ? Ne spéculons pas, mais quand ces nouveautés seront prêtes, elles sortiront en quelques mois. On se propose de présenter ces nouveautés, celles qui sont presque prêtes, celles qui seront prêtes bientôt, et celles qui ne seront pas prêtes avant un moment. Quels seront les impacts sur le langage, sur la JVM et donc sur les performances ? Que cela va-t-il nous apporter au quotidien, en tant que développeurs ? Quels seront les nouveaux patterns ? Voici le programme de cette présentation, avec des slides, du code, de la joie et de la bonne humeur !
JAX-RS and CDI Bike the (Reactive) BridgeJosé Paumard
This session explains how JAX-RS and CDI became reactive capable in Java EE 8. We put some new features of JAX-RS 2.1 and CDI 2.0 into perspective and show some reactive patterns to improve your application. Add Java 8 CompletionStage to the mix and this API trio becomes your best bet to easily go reactive without leaving the Java EE train.
The slides of my talk at Devoxx BE 2017. This in depth talk is all about collectors: those available, because we need to know them, those that we can create, those we had no idea they could be created, and the others, as there is in fact no limit to what can be done with this API. The concept of downstream collector will be used to show how we can write entire data processing pipelines using collectors only, and pass them as parameters to other pipelines.
The slides of my Java One 2017 talk about the Spliterator Patterns, or, how to extend the Stream API using the Spliterator API.
The video is available on YouTube: https://www.youtube.com/watch?v=xgHGpsubL5M
The slides of my JavaOne 2017 talk. It describes how you can create API using functional interfaces, default and static methods starting with Java 8. You can watch the video here: https://www.youtube.com/watch?v=64UO1YjVcZ0
Les slides de ma présentation à Devoxx France 2017.
Introduite en Java 8, l'API Collector vit dans l'ombre de l'API Stream, ce qui est logique puisqu'un collecteur doit se connecter à un stream pour fonctionner. Le JDK est organisé de sorte que l'on utilise surtout les collectors sur étagère : groupingBy, counting et quelques autres. Ces deux éléments masquent non seulement le modèle de traitement de données des collectors, mais aussi sa puissance et ses performances.
Ces présentation parle des collectors qui existent et qu'il faut connaître, ceux que l'on peut créer, ceux dont on se doute que l'on peut les créer une fois que l'on comprend un peu les choses, et les autres, tant les possibilités offertes par cette API sont illimitées.
The slides of my university talk, Devoxx Belgium 2016.
The goal of this talk is to compare the two most popular implementations of List: LinkedList and ArrayList, and provide hints on which one to use in what case.
The membership Module in the Odoo 17 ERPCeline George
Some business organizations give membership to their customers to ensure the long term relationship with those customers. If the customer is a member of the business then they get special offers and other benefits. The membership module in odoo 17 is helpful to manage everything related to the membership of multiple customers.
How to Add Colour Kanban Records in Odoo 17 NotebookCeline George
In Odoo 17, you can enhance the visual appearance of your Kanban view by adding color-coded records using the Notebook feature. This allows you to categorize and distinguish between different types of records based on specific criteria. By adding colors, you can quickly identify and prioritize tasks or items, improving organization and efficiency within your workflow.
Front Desk Management in the Odoo 17 ERPCeline George
Front desk officers are responsible for taking care of guests and customers. Their work mainly involves interacting with customers and business partners, either in person or through phone calls.
Beyond the Advance Presentation for By the Book 9John Rodzvilla
In June 2020, L.L. McKinney, a Black author of young adult novels, began the #publishingpaidme hashtag to create a discussion on how the publishing industry treats Black authors: “what they’re paid. What the marketing is. How the books are treated. How one Black book not reaching its parameters casts a shadow on all Black books and all Black authors, and that’s not the same for our white counterparts.” (Grady 2020) McKinney’s call resulted in an online discussion across 65,000 tweets between authors of all races and the creation of a Google spreadsheet that collected information on over 2,000 titles.
While the conversation was originally meant to discuss the ethical value of book publishing, it became an economic assessment by authors of how publishers treated authors of color and women authors without a full analysis of the data collected. This paper would present the data collected from relevant tweets and the Google database to show not only the range of advances among participating authors split out by their race, gender, sexual orientation and the genre of their work, but also the publishers’ treatment of their titles in terms of deal announcements and pre-pub attention in industry publications. The paper is based on a multi-year project of cleaning and evaluating the collected data to assess what it reveals about the habits and strategies of American publishers in acquiring and promoting titles from a diverse group of authors across the literary, non-fiction, children’s, mystery, romance, and SFF genres.
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894PECB
As artificial intelligence continues to evolve, understanding the complexities and regulations regarding AI risk management is more crucial than ever.
Amongst others, the webinar covers:
• ISO/IEC 42001 standard, which provides guidelines for establishing, implementing, maintaining, and continually improving AI management systems within organizations
• insights into the European Union's landmark legislative proposal aimed at regulating AI
• framework and methodologies prescribed by ISO/IEC 23894 for identifying, assessing, and mitigating risks associated with AI systems
Presenters:
Miriama Podskubova - Attorney at Law
Miriama is a seasoned lawyer with over a decade of experience. She specializes in commercial law, focusing on transactions, venture capital investments, IT, digital law, and cybersecurity, areas she was drawn to through her legal practice. Alongside preparing contract and project documentation, she ensures the correct interpretation and application of European legal regulations in these fields. Beyond client projects, she frequently speaks at conferences on cybersecurity, online privacy protection, and the increasingly pertinent topic of AI regulation. As a registered advocate of Slovak bar, certified data privacy professional in the European Union (CIPP/e) and a member of the international association ELA, she helps both tech-focused startups and entrepreneurs, as well as international chains, to properly set up their business operations.
Callum Wright - Founder and Lead Consultant Founder and Lead Consultant
Callum Wright is a seasoned cybersecurity, privacy and AI governance expert. With over a decade of experience, he has dedicated his career to protecting digital assets, ensuring data privacy, and establishing ethical AI governance frameworks. His diverse background includes significant roles in security architecture, AI governance, risk consulting, and privacy management across various industries, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: June 26, 2024
Tags: ISO/IEC 42001, Artificial Intelligence, EU AI Act, ISO/IEC 23894
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
Views in Odoo - Advanced Views - Pivot View in Odoo 17Celine George
In Odoo, the pivot view is a graphical representation of data that allows users to analyze and summarize large datasets quickly. It's a powerful tool for generating insights from your business data.
The pivot view in Odoo is a valuable tool for analyzing and summarizing large datasets, helping you gain insights into your business operations.
How to Install Theme in the Odoo 17 ERPCeline George
With Odoo, we can select from a wide selection of attractive themes. Many excellent ones are free to use, while some require payment. Putting an Odoo theme in the Odoo module directory on our server, downloading the theme, and then installing it is a simple process.
How to Store Data on the Odoo 17 WebsiteCeline George
Here we are going to discuss how to store data in Odoo 17 Website.
It includes defining a model with few fields in it. Add demo data into the model using data directory. Also using a controller, pass the values into the template while rendering it and display the values in the website.
Satta Matka Dpboss Kalyan Matka Results Kalyan ChartMohit Tripathi
SATTA MATKA DPBOSS KALYAN MATKA RESULTS KALYAN CHART KALYAN MATKA MATKA RESULT KALYAN MATKA TIPS SATTA MATKA MATKA COM MATKA PANA JODI TODAY BATTA SATKA MATKA PATTI JODI NUMBER MATKA RESULTS MATKA CHART MATKA JODI SATTA COM INDIA SATTA MATKA MATKA TIPS MATKA WAPKA ALL MATKA RESULT LIVE ONLINE MATKA RESULT KALYAN MATKA RESULT DPBOSS MATKA 143 MAIN MATKA KALYAN MATKA RESULTS KALYAN CHART
Kalyan Matka Kalyan Result Satta Matka Result Satta Matka Kalyan Satta Matka Kalyan Open Today Satta Matka Kalyan
Kalyan today kalyan trick kalyan trick today kalyan chart kalyan today free game kalyan today fix jodi kalyan today matka kalyan today open Kalyan jodi kalyan jodi trick today kalyan jodi trick kalyan jodi ajj ka.
Credit limit improvement system in odoo 17Celine George
In Odoo 17, confirmed and uninvoiced sales orders are now factored into a partner's total receivables. As a result, the credit limit warning system now considers this updated calculation, leading to more accurate and effective credit management.
11. @JosePaumard#Devoxx #J8Async
Difference with the synchronous multithreaded model?
1) The async engine decides to switch from one context to
another
2) Single threaded = no issue with atomicity or visibility
Performances?
No multithreaded « context switch »
Asynchronous
14. @JosePaumard#Devoxx #J8Async
Pattern
Callback or task: lambda expression
When the result is available, then we can continue with the
next task
Asynchronous
queryEngine.select("select user from User")
.forEach(user -> System.out.prinln(user)) ;
15. @JosePaumard#Devoxx #J8Async
Pattern
Callback or task: lambda expression
When the result is available, then we can continue with the
next task
Now how can we write that in Java?
Asynchronous
queryEngine.select("select user from User")
.forEach(user -> System.out.prinln(user)) ;
16. @JosePaumard#Devoxx #J8Async
A task in Java
Since Java 1: Runnable
Since Java 5: Callable
In Java 5 we have the ExecutorService (pool of threads)
We give a task and get back a Future
17. @JosePaumard#Devoxx #J8Async
A task in Java
Pattern
Callable<String> task = () -> "select user from User" ;
Future<String> future = executorService.submit(task) ;
18. @JosePaumard#Devoxx #J8Async
A task in Java
Pattern
Callable<String> task = () -> "select user from User" ;
Future<String> future = executorService.submit(task) ;
List<User> users = future.get() ; // blocking
users.forEach(System.out::println) ;
19. @JosePaumard#Devoxx #J8Async
A task in Java
Pattern
Passing an object from one task to another has to be handled
in the « master » thread
Callable<String> task = () -> "select user from User" ;
Future<String> future = executorService.submit(task) ;
List<User> users = future.get() ; // blocking
users.forEach(System.out::println) ;
25. @JosePaumard#Devoxx #J8Async
Creation of an asynchronous task
The Jersey way to create an asynchronous call
@Path("/resource")
public class AsyncResource {
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
new Thread(new Runnable() {
public void run() {
String result = longOperation();
asyncResponse.resume(result);
}
}).start();
}
}
26. @JosePaumard#Devoxx #J8Async
Creation of an asynchronous task
(let us fix this code, this is Java 8)
@Path("/resource")
public class AsyncResource {
@Inject private Executor executor;
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
executor.execute(() -> {
String result = longOperation();
asyncResponse.resume(result);
});
}
}
27. @JosePaumard#Devoxx #J8Async
How to test it?
The question is: how can we test that code?
We want to check if the result object
is passed to the resume() method of the asyncResponse
28. @JosePaumard#Devoxx #J8Async
How to test it?
We have mocks for that!
It is a very basic test, but tricky to write since we are in an
asynchronous world
29. @JosePaumard#Devoxx #J8Async
How to test it?
Let us give one more look at the code
@Path("/resource")
public class AsyncResource {
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
executor.execute(() -> { // executed in the main thread
String result = longOperation(); // executed in another thread
asyncResponse.resume(result);
});
}
}
30. @JosePaumard#Devoxx #J8Async
How to test it?
We have mocks to check if resume() is properly called with
result
It is a very basic test, but tricky to write since we are in an
asynchronous world
31. @JosePaumard#Devoxx #J8Async
How to test it?
We can inject a mock AsyncResponse, even mock the result
@Path("/resource")
public class AsyncResource {
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
executor.execute(() -> {
String result = longOperation();
asyncResponse.resume(result);
});
}
}
32. @JosePaumard#Devoxx #J8Async
How to test it?
We can inject a mock AsyncResponse, even mock the result
Then verify the correct interaction:
But:
- we need to verify this once the run() method has been
called
Mockito.verify(mockAsyncResponse).resume(result);
33. @JosePaumard#Devoxx #J8Async
How to test it?
We can inject a mock AsyncResponse, even mock the result
Then verify the correct interaction:
But:
- we need to verify this once the run() method has been
called
- and take into account the multithreaded aspect… the read /
writes on the mock should be « visible »!
Mockito.verify(mockAsyncResponse).resume(result);
34. @JosePaumard#Devoxx #J8Async
How to test it?
So our constraints are the following:
- we need to verify this once the run() method has been
called
- we need to read / write on our mocks in the same thread as
the one which runs the task we want to test
35. @JosePaumard#Devoxx #J8Async
How to test it?
This is where CompletionStage comes to the rescue!
@Path("/resource")
public class AsyncResource {
@Inject ExecutorService executor;
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
executor.submit(() -> {
String result = longOperation();
asyncResponse.resume(result);
});
}
}
36. @JosePaumard#Devoxx #J8Async
How to test it?
This pattern:
executor.submit(() -> {
String result = longOperation();
asyncResponse.resume(result);
});
37. @JosePaumard#Devoxx #J8Async
How to test it?
This pattern:
Becomes this one:
And does basically the same thing
executor.submit(() -> {
String result = longOperation();
asyncResponse.resume(result);
});
CompletableFuture.runAsync(() -> {
String result = longOperation();
asyncResponse.resume(result);
}, executor);
38. @JosePaumard#Devoxx #J8Async
How to test it?
But the nice thing is:
CompletableFuture<Void> completableFuture =
CompletableFuture.runAsync(() -> {
String result = longOperation();
asyncResponse.resume(result);
}, executor);
39. @JosePaumard#Devoxx #J8Async
How to test it?
But the nice thing is:
And on this object we can call:
CompletableFuture<Void> completableFuture =
CompletableFuture.runAsync(() -> {
String result = longOperation();
asyncResponse.resume(result);
}, executor);
completableFuture
.thenRun(() -> {
Mockito.verify(mockAsyncResponse).resume(result);
}
);
40. @JosePaumard#Devoxx #J8Async
How to test it?
Be careful of visibility issues
1) It’s simpler to run everything in the same thread
2) Create, train and check our mocks in this thread
41. @JosePaumard#Devoxx #J8Async
CompletionStage / CompletableFuture
Two elements in this API:
- an interface: CompletionStage
- an implementing class: CompletableFuture
The interface depends on CompletableFuture:
public CompletableFuture<T> toCompletableFuture();
42. @JosePaumard#Devoxx #J8Async
What is a CompletionStage?
A model for a task:
- that performs an action an may return a value when another
completion stage completes
- that may trigger other tasks
So a completion stage is an element of a chain
44. @JosePaumard#Devoxx #J8Async
What is a CompletableFuture?
A class that implements both Future and CompletionStage
It has a state:
- the task may be running
- the task may have complete normally
- the task may have complete exceptionnaly
47. @JosePaumard#Devoxx #J8Async
Methods from Future
Five methods:
boolean cancel(boolean mayInterruptIfRunning) ;
boolean isCanceled() ;
boolean isDone() ;
V get() ; // blocking call
V get(long timeout, TimeUnit timeUnit) ; // may throw a checked exception
throws InterruptedException, ExecutionException, TimeoutException ;
48. @JosePaumard#Devoxx #J8Async
More from CompletableFuture
Future-like methods:
V join() ; // may throw an unchecked exception
V getNow(V valueIfAbsent) ; // returns immediately
49. @JosePaumard#Devoxx #J8Async
More from CompletableFuture
Future-like methods:
V join() ; // may throw an unchecked exception
V getNow(V valueIfAbsent) ; // returns immediately
boolean complete(V value) ; // sets the returned value is not returned
void obtrudeValue(V value) ; // resets the returned value
50. @JosePaumard#Devoxx #J8Async
More from CompletableFuture
Future-like methods:
V join() ; // may throw an unchecked exception
V getNow(V valueIfAbsent) ; // returns immediately
boolean complete(V value) ; // sets the returned value is not returned
void obtrudeValue(V value) ; // resets the returned value
boolean completeExceptionnaly(Throwable t) ; // sets an exception
void obtrudeException(Throwable t) ; // resets with an exception
51. @JosePaumard#Devoxx #J8Async
How to create a CompletableFuture?
A completed CompletableFuture
public static <U> CompletableFuture<U> completedFuture(U value) ;
52. @JosePaumard#Devoxx #J8Async
How to create a CompletableFuture?
A CompletableFuture from a Runnable or a Supplier
public static CompletableFuture<Void>
runAsync(Runnable runnable, Executor executor) ;
public static <U> CompletableFuture<U>
supplyAsync(Supplier<U> value, Executor executor) ;
53. @JosePaumard#Devoxx #J8Async
Building CompletionStage chains
A CompletionStage is a step in a chain
- it can be triggered by a previous CompletionStage
- it can trigger another CompletionStage
- it can be executed in a given Executor
55. @JosePaumard#Devoxx #J8Async
Building CompletionStage chains
What kind of operation does it support?
- chaining (1 – 1)
- composing (1 – 1)
- combining, waiting for both result (2 – 1)
- combining, triggered on the first available result (2 – 1)
56. @JosePaumard#Devoxx #J8Async
Building CompletionStage chains
What kind of operation does it support?
- chaining (1 – 1)
- composing (1 – 1)
- combining, waiting for both result (2 – 1)
- combining, triggered on the first available result (2 – 1)
All this gives… 36 methods!
57. @JosePaumard#Devoxx #J8Async
Building CompletionStage chains
In what thread can it be executed?
- In the same executor as the caller
- In a new executor, passed as a parameter
- Asynchronously, ie in the common fork join pool
All this gives… 36 methods!
59. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some 1 – 1 patterns
public <U> CompletionStage<U>
thenApply(Function<? super T,? extends U> fn);
public CompletionStage<Void>
thenRunAsync(Runnable action, Executor executor);
60. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some 1 – 1 patterns
public <U> CompletionStage<U>
thenApply(Function<? super T,? extends U> fn);
public CompletionStage<Void>
thenRunAsync(Runnable action, Executor executor);
public CompletionStage<Void>
thenComposeAsync(
Function<? super T, ? extends CompletionStage<U>> fn);
61. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some 2 – 1 patterns
public <U, V> CompletionStage<V> thenCombineAsync
(CompletionStage<U> other,
BiFunction<T, U, V> function) ;
62. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some 2 – 1 patterns
public <U, V> CompletionStage<V> thenCombineAsync
(CompletionStage<U> other,
BiFunction<T, U, V> function) ;
public <U> CompletionStage<Void> thenAcceptBoth
(CompletionStage<U> other,
BiConsumer<T, U> action) ;
63. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some 2 – 1 patterns
public <U, V> CompletionStage<V> thenCombineAsync
(CompletionStage<U> other,
BiFunction<T, U, V> function) ;
public <U> CompletionStage<Void> thenAcceptBoth
(CompletionStage<U> other,
BiConsumer<T, U> action) ;
public CompletionStage<Void> runAfterBothAsync
(CompletionStage<?> other,
Runnable action, Executor executor) ;
64. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some more 2 – 1 patterns
public <U> CompletionStage<U> applyToEither
(CompletionStage<? extends T> other,
Function<T, U> function) ;
65. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some more 2 – 1 patterns
public <U> CompletionStage<U> applyToEither
(CompletionStage<? extends T> other,
Function<T, U> function) ;
public CompletionStage<Void> acceptEitherAsync
(CompletionStage<? extends T> other,
Consumer<? extends T> consumer) ;
66. @JosePaumard#Devoxx #J8Async
CompletionStage – patterns
Some more 2 – 1 patterns
public <U> CompletionStage<U> applyToEither
(CompletionStage<? extends T> other,
Function<T, U> function) ;
public CompletionStage<Void> acceptEitherAsync
(CompletionStage<? extends T> other,
Consumer<? extends T> consumer) ;
public CompletionStage<Void> runAfterEitherAsync
(CompletionStage<U> other,
Runnable action, Executor executor) ;
67. @JosePaumard#Devoxx #J8Async
Back to our first example
So the complete pattern becomes this one
1) First we create our mocks
String result = Mockito.mock(String.class);
AsyncResponse response = Mockito.mock(AsyncResponse.class);
Runnable train = () -> Mockito.doReturn(result).when(response).longOperation();
Runnable verify = () -> Mockito.verify(response).resume(result);
68. @JosePaumard#Devoxx #J8Async
Back to our first example
So the complete pattern becomes this one
2) Then we create the call & verify
Runnable callAndVerify = () -> {
asyncResource.executeAsync(response).thenRun(verify);
}
69. @JosePaumard#Devoxx #J8Async
Back to our first example
So the complete pattern becomes this one
3) Then we create the task
ExecutorService executor = Executors.newSingleThreadExecutor();
AsyncResource asyncResource = new AsyncResource();
asyncResource.setExecutorService(executor);
CompletableFuture
.runAsync(train, executor) // this trains our mocks
.thenRun(callAndVerify); // this verifies our mocks
70. @JosePaumard#Devoxx #J8Async
Back to our first example
Since a CompletableFuture is also a Future, we can fail with
a timeout if the test does not complete fast enough
ExecutorService executor = Executors.newSingleThreadExecutor();
AsyncResource asyncResource = new AsyncResource();
asyncResource.setExecutorService(executor);
CompletableFuture
.runAsync(train, executor) // this trains our mocks
.thenRun(callAndVerify) // this verifies our mocks
.get(10, TimeUnit.SECONDS);
72. @JosePaumard#Devoxx #J8Async
A second example
Async analysis of a web page
CompletableFuture.supplyAsync(
() -> readPage("http://whatever.com/")
)
.thenApply(page -> linkParser.getLinks(page))
73. @JosePaumard#Devoxx #J8Async
A second example
Async analysis of a web page
CompletableFuture.supplyAsync(
() -> readPage("http://whatever.com/")
)
.thenApply(page -> linkParser.getLinks(page))
.thenAccept(
links -> displayPanel.display(links) // in the right thread!
) ;
74. @JosePaumard#Devoxx #J8Async
A second example
Async analysis of a web page
CompletableFuture.supplyAsync(
() -> readPage("http://whatever.com/")
)
.thenApply(page -> linkParser.getLinks(page))
.thenAcceptAsync(
links -> displayPanel.display(links),
executor
) ;
76. @JosePaumard#Devoxx #J8Async
A second example
Async analysis of a web page
public interface Executor {
void execute(Runnable command);
}
Executor executor = runnable -> SwingUtilities.invokeLater(runnable) ;
77. @JosePaumard#Devoxx #J8Async
A second example
Async analysis of a web page
CompletableFuture.supplyAsync(
() -> readPage("http://whatever.com/")
)
.thenApply(page -> linkParser.getLinks(page))
.thenAcceptAsync(
links -> displayPanel.display(links),
runnable -> SwingUtilities.invokeLater(runnable)
) ;
78. @JosePaumard#Devoxx #J8Async
A second example
Async analysis of a web page
CompletableFuture.supplyAsync(
() -> readPage("http://whatever.com/")
)
.thenApply(Parser::getLinks)
.thenAcceptAsync(
DisplayPanel::display,
SwingUtilities::invokeLater
) ;
79. @JosePaumard#Devoxx #J8Async
A last example
Async events in CDI
@Inject
Event<String> event ;
event.fire("some event") ; // returns void
public void observes(@Observes String payload) {
// handle the event, called in the firing thread
}
80. @JosePaumard#Devoxx #J8Async
A last example
Async events in CDI
public void observes(@Observes String payload) {
// handle the event, called in the firing thread
CompletableFuture.anyOf(/* some task */) ;
}
81. @JosePaumard#Devoxx #J8Async
A last example
Async events in CDI
@Inject
Event<String> event ;
event.fireAsync("some event") ; // returns CompletionStage<Object>
public void observes(@ObservesAsync String payload) {
// handle the event in another thread
}
82. @JosePaumard#Devoxx #J8Async
A last example
Async events in CDI
@Inject
Event<String> event ;
Executor executor = SwingUtilities::invokeLater
event.fireAsync("some event", executor) ;
83. @JosePaumard#Devoxx #J8Async
A last example
Async events in CDI
@Inject
Event<String> event ;
Executor executor = SwingUtilities::invokeLater
CompletionStage<Object> cs =
event.fireAsync("some event", executor) ;
cs.whenComplete(...); // handle the exceptions
84. @JosePaumard#Devoxx #J8Async
CompletionStage – last patterns
Static methods
public static CompletableFuture<Void>
allOf(CompletableFuture<?>... cfs) ;
public static CompletableFuture<Object>
anyOf(CompletableFuture<?>... cfs) ;
91. @JosePaumard#Devoxx #J8Async
Exception handling
Which means that:
- the call to isCompletedExceptionnaly() returns true
- the call to get() throws an ExecutionException which cause
is the root Exception
CompletableFuture can handle exceptions
95. @JosePaumard#Devoxx #J8Async
Exception handling
Suppose CF30 has been created with exceptionnaly()
If CF21 completes normally, then CF30 just transmits the value
If it raises an exception, then CF30 handles it and generate a
value for CF31
CF1 CF21
CF22
CF31
CF32
CF41
exceptionnaly()
CF30
97. @JosePaumard#Devoxx #J8Async
Exception handling
There are three methods to handle an exception
handle() has also asynchronous versions
CompletionStage<T> exceptionally(
Function<Throwable, ? extends T> function);
<U> CompletionStage<U> handle(
BiFunction<? super T, Throwable, ? extends U> bifunction);
98. @JosePaumard#Devoxx #J8Async
Exception handling
There are three methods to handle an exception
whenComplete() has also asynchronous versions
CompletionStage<T> exceptionally(
Function<Throwable, ? extends T> function);
<U> CompletionStage<U> handle(
BiFunction<? super T, Throwable, ? extends U> bifunction);
CompletionStage<T> whenComplete(
BiConsumer<? super T, Throwable> action);
99. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
100. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
manyStrings
.onClose(() -> { closing.complete(""); })
101. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
manyStrings
.onClose(() -> { closing.complete(""); })
.map(CompletableFuture::completedFuture)
102. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
manyStrings
.onClose(() -> { closing.complete(""); })
.map(CompletableFuture::completedFuture)
.filter(cf -> cf.get().length() < 20)
103. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
manyStrings
.onClose(() -> { closing.complete(""); })
.map(CompletableFuture::completedFuture)
.filter(cf -> cf.get().length() < 20)
.reduce(
closing,
(cf1, cf2) -> cf1.thenCombine(cf2, binaryOperator) // concatenation
);
104. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
CompletableFuture<String> reduce =
manyStrings
.onClose(() -> { closing.complete(""); })
.map(CompletableFuture::completedFuture)
.filter(cf -> cf.get().length() < 20)
.reduce(
closing,
(cf1, cf2) -> cf1.thenCombine(cf2, binaryOperator) // concatenation
);
105. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
CompletableFuture<String> reduce =
manyStrings
.onClose(() -> { closing.complete(""); })
.map(CompletableFuture::completedFuture)
.filter(cf -> cf.get().length() < 20)
.reduce(
closing,
(cf1, cf2) -> cf1.thenCombine(cf2, binaryOperator) // concatenation
);
manyStrings.close();
106. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
CompletableFuture<String> reduce =
manyStrings
.onClose(() -> { closing.complete(""); })
.map(CompletableFuture::completedFuture)
.filter(cf -> cf.get().length() < 20)
.reduce(
closing,
(cf1, cf2) -> cf1.thenCombine(cf2, binaryOperator) // concatenation
);
manyStrings.close();
107. @JosePaumard#Devoxx #J8Async
A very last example
CompletableFuture<String> closing = new CompletableFuture<String>() ;
Stream<String> manyStrings = Stream.of("one", "two", "three") ;
CompletableFuture<String> reduce =
manyStrings.parallel()
.onClose(() -> { closing.complete(""); })
.map(CompletableFuture::completedFuture)
.filter(cf -> cf.get().length() < 20)
.reduce(
closing,
(cf1, cf2) -> cf1.thenCombine(cf2, binaryOperator) // concatenation
);
manyStrings.close();
113. @JosePaumard#Devoxx #J8Async
Conclusion
We have an API for async computations in the JDK!
Very rich, many methods which makes it complex
Built on lambdas
Gives a fine control over threads
114. @JosePaumard#Devoxx #J8Async
Conclusion
We have an API for async computations in the JDK!
Very rich, many methods which makes it complex
Built on lambdas
Gives a fine control over threads
Handle chaining, composition
115. @JosePaumard#Devoxx #J8Async
Conclusion
We have an API for async computations in the JDK!
Very rich, many methods which makes it complex
Built on lambdas
Gives a fine control over threads
Handle chaining, composition
Very clean way of handling exceptions