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 !
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 !
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
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 !
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
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 Records (including Records serialization), Pattern Matching for `instanceof`, switch expression, sealed classes, and hidden classes. 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 APsI. You will discover record patterns, array patterns, as well as deconstruction patterns, through constructors, factory methods, and deconstructors.
You can find the code shown here: https://github.com/JosePaumard/devoxx-uk-2021
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!
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
Slides from the talk we did with Maurice Naftalin for Devoxx Belgium 2019.
Functional programmers have been saying for decades that they know the way to the future.
Clearly they have been wrong, since imperative languages are still far more popular.
Clearly they have also been right, as the advantages of functional programming have become increasingly obvious. Is it possible to face both ways, and 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 will review what Java has learned from functional languages, what it can still learn, and how its added features compare to Scala's original ones.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
StxNext Lightning Talks - Feb 12, 2016
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice when it comes to Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and on the other - keeping short compile times.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up an Android-kotlin project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin usage is presented and the language is compared to SCALA and SWIFT.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
Bogdan Hodorog's presentation on Practical Functional Programming at the Functional Angle Meetup help at 3Pillar's office in Timisoara. Bogdan Hodorog is a Software Engineer who is passionate about building, trying, and playing with software...of all sorts. He currently specializes in Python but is interested in programming languages ad operating systems of all kinds.
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
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 Records (including Records serialization), Pattern Matching for `instanceof`, switch expression, sealed classes, and hidden classes. 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 APsI. You will discover record patterns, array patterns, as well as deconstruction patterns, through constructors, factory methods, and deconstructors.
You can find the code shown here: https://github.com/JosePaumard/devoxx-uk-2021
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!
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
Slides from the talk we did with Maurice Naftalin for Devoxx Belgium 2019.
Functional programmers have been saying for decades that they know the way to the future.
Clearly they have been wrong, since imperative languages are still far more popular.
Clearly they have also been right, as the advantages of functional programming have become increasingly obvious. Is it possible to face both ways, and 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 will review what Java has learned from functional languages, what it can still learn, and how its added features compare to Scala's original ones.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
StxNext Lightning Talks - Feb 12, 2016
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice when it comes to Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and on the other - keeping short compile times.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up an Android-kotlin project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin usage is presented and the language is compared to SCALA and SWIFT.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
Bogdan Hodorog's presentation on Practical Functional Programming at the Functional Angle Meetup help at 3Pillar's office in Timisoara. Bogdan Hodorog is a Software Engineer who is passionate about building, trying, and playing with software...of all sorts. He currently specializes in Python but is interested in programming languages ad operating systems of all kinds.
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
In this WebHack talk I shared about what I have learnt from SpiderMonkey: the JavaScript engine inside Firefox browser. I extracted and concluded 3 slides made in the past, and updated some few content.
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
HotSpot promises to do the "right" thing for us by identifying our hot code and compiling "just-in-time", but how does HotSpot make those decisions?
This presentation aims to detail how HotSpot makes those decisions and how it corrects its mistakes through a series of demos that you run yourself.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
This is the second and last part of the large article about analysis of the Haiku operating system. In the first article, we discussed a variety of possible errors all of which one way or another deal with conditions. In this article, we will discuss the remaining analyzer warnings I have selected for you. The bug examples are grouped into several categories.
After reimplement many features several times in different platforms is time to think that it should be a better way. There are many frameworks that allows the developers to write the code once and deploy it "everywhere", but the final result is an app with a non native look and feel or with an emulated look and feel that the users can see and rate according to the quality.
There are other ways to develop apps for multiple platforms without rewriting the same code over and over. I'll talk about one of that ways which consists on developing the core with C++ and implement the UI natively. This method could sound very scary because of the C++ reputation (memory leaks, the standard library, etc), but with C++11 all this has been improved in a very sweet way, so maybe it is time to take an other look at this language and see how can we take advantage of it.
Building High-Performance Language Implementations With Low EffortStefan Marr
This talk shows how languages can be implemented as self-optimizing interpreters, and how Truffle or RPython go about to just-in-time compile these interpreters to efficient native code.
Programming languages are never perfect, so people start building domain-specific languages to be able to solve their problems more easily. However, custom languages are often slow, or take enormous amounts of effort to be made fast by building custom compilers or virtual machines.
With the notion of self-optimizing interpreters, researchers proposed a way to implement languages easily and generate a JIT compiler from a simple interpreter. We explore the idea and experiment with it on top of RPython (of PyPy fame) with its meta-tracing JIT compiler, as well as Truffle, the JVM framework of Oracle Labs for self-optimizing interpreters.
In this talk, we show how a simple interpreter can reach the same order of magnitude of performance as the highly optimizing JVM for Java. We discuss the implementation on top of RPython as well as on top of Java with Truffle so that you can start right away, independent of whether you prefer the Python or JVM ecosystem.
While our own experiments focus on SOM, a little Smalltalk variant to keep things simple, other people have used this approach to improve peek performance of JRuby, or build languages such as JavaScript, R, and Python 3.
The final dream of every developer is creating his own programming language. Today it is possible to realize that dream with a reasonable effort. In addition to that is also possible to leverage the JVM to make a language that can reuse a huge amount of libraries. In this presentation we are going to see what elements do we need to build our own language, with a compiler for the JVM. This is not only a lot of fun but it can be also useful in practice, to build Domain Specific Languages that compiles to bytecode and can be used together with mainstream languages in larger applications.
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.
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.
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!
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.
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 slides of my JavaOne 2016 talk. This talk is a tutorial on how to write lambda expressions, how to compose them using default methods in functional interfaces, and how to create factory methods in those interfaces. Many examples and patterns are provided.
ArrayList et LinkedList sont dans un bateauJosé Paumard
Slides de mon université à Devoxx France 2016. Le sujet est la performance des algorithmes d'implémentation de List et leur adéquation avec la structure des CPU actuels.
Slides of the talk we made with David Delabasee (@delabassee) at Devoxx 2015. A list of Java SE 8 patterns that you can use in Java EE 7 applications, thanks to the support of the major app servers.
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
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.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
5. var local type var inference
10
11 var as lambda parameters raw string nestmatescondy
inner classes
private in VM
6. 11 var as lambda parameters nestmatescondy
inner classes
private in VM
12 expr switch
type switch record
const lambda
7. 11 var as lambda parameters nestmatescondy
inner classes
private in VM
12 expr switch
type switch record
const lambda
13+
sealed interface
pattern matching
value type
raw string
8. Public Poll!
You can get Kahoot! to participate in the poll, just before
the coffee break
11. Anatomy of a Java Distribution
Language Tools
– compiler: javac, ecj
– jshell, jlink, javadoc, javap, jdb, etc
Runtime Environment
– A class library: OpenJDK, Harmony (discontinuated)
– A virtual Machine: Hotspot, J9
●
Bytecode compiler: c1 / c2, graal (java), falcon (llvm)
●
Garbage collector: CMS / G1 / ZGC, shenandoah, c4
12. Graal
A Java bytecode compiler written in Java
JVM Compiler Interface (JEP 243)
– Interface between the VM and the bytecode compiler
– Hotspot and J9 support JVMCI (since Java 9)
But Graal recompiles itself at the same time it compiles the
application ?
13. Graal JIT + AOT
Two configurations
– Just in Time Compiler (like c1 and c2)
– Ahead of Time Compiler (like any C compilers)
Graal compiles itself ahead of time (since april 2019)
– libgraal (shared library)
– Clean separation of the memory resource
14. Trade off between JIT vs AOT
JIT knows runtime informations
– Exact CPU version
– Application Profiling (delayed JIT)
– Can not use slow optimizations
AOT knows all the codes
– Fast startup time, lower runtime overhead
– No dynamic support (no dynamic classloading, no bytecode generation)
– Can not use optimizations that generates too much assembly codes
15. What About the JIT Performances ?
Let us take a well-known benchmark:
The computation of the Mandelbrot set
Easy!
16. Julia Sets
Comes from the Julia set:
For a given value of c, this is the set of z0
For which zn+1 = zn
2 + c is bound
If |zn| becomes greater than 2
Then z0 does not belong to
the Julia set
18. Computing the Mandelbrot Set
Make each point of an image a complex number c
Compute the following:
z0 = 0
zn+1 = zn
2 + c
If for some n, |zn| becomes greater than 2
Then c does not belong to the Mandelbrot set
19. Computing the Mandelbrot Set
Implementation: take an image of size 64x64
For each pixel z
If n reaches 1000 and |zn| stays lower than 2
Then the point belongs to the set
So there are about 16M multiplications to be made
All the multiplications are different
20. Computing the Mandelbrot Set
Complex provides a useful abstraction
for (var col = -32; col < +32; col++) {
for (var row = -32; row < +32; row++) {
var c = new Complex(col, row);
var zn = new Complex(0.0, 0.0);
var iteration = 0;
while (zn.modulus() < 4 && iteration < max) {
zn = zn.square().add(c);
iteration++;
}
if (iteration < max) {
image.setRGB(col, row, colors[iteration]);
} else {
image.setRGB(col, row, black);
}
}
}
21. Computing the Mandelbrot Set
Computing the Mandelbrot set C style
for (var col = -32; col < +32; col++) {
for (var row = -32; row < +32; row++) {
var an = 0.0; var bn = 0.0;
var iteration = 0;
while (an*an + bn*bn < 4 && iteration < max) {
var next_a = an*an - bn*bn + col;
var next_b = 2*an*bn + row;
an = next_a; bn = next_b;
iteration++;
}
if (iteration < max) {
image.setRGB(col, row, colors[iteration]);
} else {
image.setRGB(col, row, black);
}
}
}
22. JIT Performance with JMH
Time to render Mandelbrot 64x64
With jdk 11 (c1 + c2)
score error
primitive 1540 µs/op 22 µs/op
reference 2816 µs/op 48 µs/op
23. JIT Performance with JMH
Time to render Mandelbrot 64x64
libgraal (ce-rc15) -XX:+UseJVMCICompiler
score error
primitive 1544 µs/op 10 µs/op
reference 1542 µs/op 7 µs/op
24. GraalVM: a Java 8 Distribution
Language Tools
– compiler: javac, ecj
– jshell, jlink, javadoc, javap, jdb, native-image, etc
Runtime Environment
– A class library: OpenJDK + Truffle
– A virtual Machine: Hotspot
●
Bytecode compiler: c1 / c2, graal (java)
●
Garbage collector: CMS / G1 / ZGC
– A C backend optimizer: llvm
25. native-image
Precompile a JVM-based application into one executable
Use Graal AOT + SubstrateVM
SubstrateVM
– Low memory footprint VM
– No dynamic linking support
– Use low pause non generationnal GC
Support Java, Scala, Kotlin, Clojure
26. Truffle
Write an interpreter with some specialization machinery to help
the partial evaluator (Graal), get a compiler for free
Truffle is a Java library
– runs on Hotspot or Substrate VM
– ask Graal to aggressively optimize the code
– Allows (dynamic) languages interoperability at runtime
27. In a Nutshell
A Java 8 application can be executed on:
1) HotSpot with C1 / C2 as JIT compilers
2) HotSpot with Graal as JIT compiler
3) A Jlink generated JRE with HotSpot
4) A native image, AOT compiled with Graal,
executed on SubstrateVM
28. What Do You Need to Compare ?
How much time it takes to link the application ?
The size of the application ?
How fast does it execute ?
29. Link-time, run-time & storage
scan rt.jar and compute stats
link-time run-time storage
jdk11 - 1.70 s 288 k (304 M)
jdk8 + libgraal - 1.32 s 288 k (878 M)
jdk11 + jlink 2.2 s 1.53 s 43 M
native-image 22 s (43s) 0.79 s 10 M
30. OpenJDK Project Metropolis
Rewrite Hotspot in Java
Use libgraal as JIT to replace c1/c2
Rewrite the runtime in Java
Interpreter in Java ?
Rewrite the GCs in Java
Need a JVMGCI ?
33. Stack allocation in C
C allows stack allocation
typedef struct _complex {
double re;
double im;
} complex;
complex c; // allocate re and im on stack
Abstraction with no allocation cost !
34. Aliasing and Stack
If structs are passed as pointers, the compiler doesn’t know
if it’s the same address is in memory or not
void foo(complex* c1, complex* c2) {
c1 -> re = 5;
// does c2 -> re has been changed or not ?
}
In Java, you can not create an address on stack
Because the VM re-arranges the stack frames at runtime
35. Value class
A simple immutable class tagged as value
public value class Complex {
private final double re;
private final double im;
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
public Complex add(Complex c) {
return new Complex(re + c.re, im + c.im);
}
}
36. Value type
Immediate value with no header
– Immutable and final
– No identity (no address in heap)
– Non null
– Can implement interfaces
Motto: “Code like a class, works like an int”
37. Back to the Mandelbrot Set
Complex provides a useful abstraction
for (var col = -32; col < +32; col++) {
for (var row = -32; row < +32; row++) {
var c = new Complex(row, col);
var zn = new Complex(0.0, 0.0);
var iteration = 0;
while (zn.modulus() < 4 && iteration < max) {
zn = zn.square().add(c);
iteration++;
}
if (iteration < max) {
image.setRGB(col, row, colors[iteration]);
} else {
image.setRGB(col, row, black);
}
}
}
39. JMH
How much time to render the Mandelbrot 64x64 with 1000
iterations?
With java -XX:+EnableValhalla
score error
primitive 1540 µs/op 22 µs/op
reference 2816 µs/op 48 µs/op
value 1541 µs/op 12 µs/op
40. Optional/Option
public value class Option<E> {
private final E value;
private Option(E value) {
this.value = value;
}
public static <E> Option<E> empty() {
return Option<E>.default;
}
public static <E> Option<E> of(E value) {
Objects.requireNonNull(value);
return new Option<>(value);
}
public static <E> Option<E> ofNullable(E value) {
return (value == null)? empty(): of(value);
}
...
All fields are 0, null, 0.0, etc
42. Benchmark with JMH
private static final Map<String, Integer> MAP = Map.of("foo", 1, "bar", 2, "baz", 3);
private static final List<String> LIST = List.of("a", "foo", "b", "bar", "c", "baz");
@Benchmark
public int sum_null() {
int sum = 0;
for(var key: LIST) {
var value = MAP.get(key);
sum += (value != null)? value: 0;
}
return sum;
}
@Benchmark
public int sum_optional() {
int sum = 0;
for(var key: LIST) {
var value = Optional.ofNullable(MAP.get(key));
sum += value.orElse(0);
}
return sum;
}
43. Benchmark with JMH
public final class value Option<E> {
private final E value;
private Option(E e) {
this.e = e;
}
public Option<E> of(E e) {
Objects.requireNonNull(e);
return new Option<>(e);
}
public static <E> Option<E> empty() {
return Option<E>.default;
}
public static <E> Option<E> ofNullable(E value) {
return (value == null)? empty(): of(value);
}
/* rest of the class */
}
@Benchmark
public int sum_option() {
int sum = 0;
for(var key: LIST) {
var value = Option.ofNullable(MAP.get(key));
sum += value.orElse(0);
}
return sum;
}
44. JMH
Time to compute the sum
With java -XX:+EnableValhalla
score error
sum_null 60.9 ns/op 0.9 ns/op
sum_optional 71.6 ns/op 3.6 ns/op
sum_option 61.3 ns/op 0.4 ns/op
45. Classes are not immutable
Problem: a class is not truly immutable
– You can see the field being initialized in the constructor
Only initialize through static factory
– Add 2 new opcodes: default/with
– Let the compiler do the lifting
But not binary compatible => bridges ??
46. Constructor are static factory
public value class IntBox {
private final int value;
private IntBox(int value) {
this.value = value;
}
public int intValue() {
return value;
}
public static IntBox zero() {
return IntBox.default;
}
public static IntBox valueOf(int value) {
var box = IntBox.default;
box = __WithField(box.value, value);
return box;
}
} WithField allows to change one field
47. Flattenable
Storing a value type in a field or an array
– Less pointer chasing!
Problems
– with volatile field
●
don’t flatten if volatile
– When writing without synchronized or volatile
●
value type tearing :(
48. Array flattening ?
Array of value types are flattenable
– Don’t flatten if too big !
header header
header
header
header
An array of java.lang.Integer An array of IntBox
50. Benchmark
Sum of an array of value type
private static final IntBox[] ARRAY = new IntBox[100_000];
static {
range(0, ARRAY.length).forEach(i -> ARRAY[i] = IntBox.valueOf(i));
}
@Benchmark
public int sum_IntBox() {
var sum = 0;
for(var value : ARRAY) {
sum += value.intValue();
}
return sum;
}
51. JMH
Time to sum an array of 100 000 values
With java -XX:+EnableValhalla
score error
primitive (int) 27.1 µs/op 0.2 µs/op
reference (Integer) 60.7 µs/op 0.6 µs/op
Value (IntBox) 27.0 µs/op 0.1 µs/op
52. Benchmark
What if we shuffle the values ?
private static final IntBox[] ARRAY = new IntBox[100_000];
static {
range(0, ARRAY.length).forEach(i -> ARRAY[i] = IntBox.valueOf(i));
Collections.shuffle(Arrays.asList(ARRAY));
}
@Benchmark
public int sum_IntBox() {
var sum = 0;
for(var value : ARRAY) {
sum += value.intValue();
}
return sum;
}
53. JMH
Time to sum an array of 100 000 random values
With java -XX:+EnableValhalla
score error
primitive (int) 27.1 µs/op 0.2 µs/op
reference (Integer) 121.9 µs/op 5.1 µs/op
Value (IntBox) 27.0 µs/op 0.1 µs/op
54. First Prototype
Minimum Value Type
– Reference Object can be
unboxed to a value type
– Value type are not subtype of
Object
●
Need to box first
55. Second Prototype
L-World
– Subtypes of Object
doesn’t work exactly like an int
:(
Minimum Value Type
– Reference Object can be
unboxed to a value type
– Value type are not subtype of
Object
●
Need to box first
56. L-world issues
Operations that requires an object header
● synchronized throws IllegalStateMonitorException
●
==
– opt-in to component-wise comparison or
– always false
Arrays are covariant
●
Array access are polymorphic :(
– The JIT try to aggressively hoist the element check
57. L-world issues : Generics
Erased so no flattening
●
Reify generics over value types
A type parameter can be null
●
Need a nullable value type for old generics
Complex?, IntBox?
58. L-world Issues : Concurrency
Value types are subjects of tearing
public value class SecurityToken {
private final long id1, id2;
public SecurityToken(long id1, long id2) {
if (id1 != id2) throw new IllegalArgumentException();
...
}
public void check() {
if (id1 != id2) throw new IllegalStateException();
}
public static void main(String[] args) {
var tokens = new SecurityToken[1];
IntStream.range(0, 2).forEach(id -> {
new Thread(() -> {
for(;;) {
tokens[0].check();
tokens[0] = new SecurityToken(id, id);
}
}).start();
});
} }
64. Erlang Actor
Scheduled by the Erlang VM (BEAM)
counter(Sum) ->
receive % wait for some message
{increment} ->
counter(Sum+1); % tail-call
{value} ->
io:format("~p~n", [Sum]);
end.
pid ! {increment}; % send a message to pid
65. Thread are heavyweight !
A Thread
– Share the same address space
– Lightweight Lock
●
no context switch
but
– Thread stack is pre-reserved (=> OOM if a lot of threads)
– Thread scheduling is done by the OS !
67. Continuation
Wrap a Runnable
Continuation.run() execute the runnable
– Can stop itself with a yield !
– A call to run() will restart the runnable
just after the yield
No language support needed
68. A simple example
Create a continuation and run it
var scope = new ContinuationScope("example");
var continuation = new Continuation(scope, () -> {
System.out.println("hello Devoxx France");
});
System.out.println("start continuation");
continuation.run();
69. A simple example
Create a continuation and call run(), yield(), run()
var scope = new ContinuationScope("example");
var continuation = new Continuation(scope, () -> {
System.out.println("hello Devoxx France");
Continuation.yield(scope);
System.out.println("i’m back !");
});
System.out.println("start continuation");
continuation.run();
System.out.println("restart continuation");
continuation.run();
70. How does it work ?
Yield copy the all stack frames on heap !
main
run
f1
f2
heap
run
f1
f2
71. How does it work ?
Then run() move some stack frames back
main
f2
heap
stack bang!
The VM tries to guess
how many stack frames
should be moved
A read of the stack bang
trigger the copy of the
remaining frames
72. Delimited Continuation vs Thread
Scheduling explicit (yield, run)
– No OS context switch
No heap reservation
– Only store what is actually needed !
73. Erlang Actor
Scheduled by the Erlang VM (BEAM)
counter(Sum) ->
receive % wait for some message
{increment} ->
counter(Sum+1); % tail-call
{value} ->
io:format("~p~n", [Sum]);
end.
pid ! {increment}; % send a message to pid
74. Java Actor ?
Scheduled by the JVM/JDK
var actor = new Actor(new Runnable() {
int sum;
public void run() {
while (true) {
receive(message -> { // wait for some message
switch((String)message {
case "increment" ->
sum++; // side effect
case "value" -> {
System.out.println(sum);
exit();
}
}});
}
}});
actor.send("increment"); // send a message to the actor
77. Fiber
Wrap a Runnable
Scheduled using an ExecutorService
– A fiber is scheduled on a thread
Blocking calls (read, write, sleep)
– Freeze the fiber, schedule another one
– Re-scheduled
●
When a read/write/locks/etc will not block
●
Maybe scheduled on another thread
78. Fiber vs Continuation
A fiber delegates the suspension (yield) to the continuation
– All blocking calls do internally a yield
– The JDK code calls run() on the continuation
when it can be rescheduled
All the JDK needs to be patched to be “fiber aware”
79. Fiber/Continuation limitation
Continuation/Fiber
– Can not yield if there is a native frame on the stack
Fiber
– Yielding inside a synchronized block pins the fiber to that thread
●
The same thread as to be used when re-scheduling
●
This limitation may be removed in the future
80. Thread related API ?
Some Thread related APIs need to be reworked
Thread.currentThread()
– Need to lazily create a fake thread per fiber :(
ThreadLocal/InheritableThreadLocal
– Redirect thread local to fiber locals
Will consume a lot of memory
81. Roadmap
Tailcall support ?
– Not implemented yet
Performance ?
– Still a prototype !
No version of Java targeted, yet !
84. Precise type inference
Groovy (with @CompileStatic) change the type of a variable after
an instanceof
Object x = ...
if (x instanceof String) {
print(x.length()); // x is a String here !
}
// x is not a String here !
85. Instanceof in Java
Extends the intanceof syntax to define a new variable
Object x = ...
if (x instanceof String s) {
System.out.println(s.length());
}
Avoid to introduce an intersection type
if (x instanceof I || x instanceof J) { … }
86. Declaration/Definition
The rules for declaration/definition are a little surprising
class Point {
private final int x;
private final int y;
…
@Override
public boolean equals(Object o) {
if (!(o instanceof Point p) {
return false;
}
return x == p.x && y == p.y;
}
...
}
declaration
definition
87. Declaration/Definition
Other examples
if (x instanceof String s && s.length() == 3) { …
if (x instanceof String s || foo()) { /* no s here */ }
(x instanceof String s)? s.length(): /* no s here */
while(x instanceof String s) {
… s.length()
}
90. Data storage class
Sometimes a class is just a storage for data
In Java, you get encapsulation by default,
So you need to declare fields, write boring constructors, boring getters,
boring equals, hashCode and toString
91. While in Kotlin
you have data class
data class User(val name: String, val age: Int)
the compiler generates
constructor, getters/setters, equals(), hashCode() and
toString()
92. Known problems
Data class in Kotlin
Can be mutable
So storing data class is a HashSet/HashMap
is a mess
You can still declare fields
There are not used in equals/hashCode/toString ??
The boilerplate code is still there on disk
93. Record in Java
record User(String name, int age)
A record (a data carrier)
is non mutable
generates overridable
●
Constructor, accessors: String name(), int age()
●
equals/hashCode/toString
– Implementation is provided by invokedynamic
has no supplementary fields
94. An example
The primary constructor can specify pre-conditions
public record User(String name, int age) {
public User {
Objects.requireNonNull(name);
}
public boolean isOld() {
return age > 14;
}
}
95. Record vs other features
A record can be combined with a value type
value record User(String name, int age)
the keyword “value” acts as a modifier
Records will have a special support for pattern matching
(using extractors)
97. Abstract data type in Haskell
A function is defined as a list of pattern matchs
data Expr = Value Int | Add Expr Expr
eval :: Expr -> Int
eval (Value v) = v
eval (Add l r) = eval(l) + eval(r)
98. Rough translation in Java
New features: sealed interface + switch expression
sealed interface Expr {
record Value(int v) implements Expr;
record Add(Expr l, Expr r) implements Expr;
}
int eval(Expr expr) {
return switch(expr) {
case Value(var v) -> v;
case Add(var l, var r) -> eval(l) + eval(r);
};
}
100. What’s wrong with switch ?
String[] tokens = ...
Vehicle vehicle;
switch(tokens[0]) {
case "car":
case "sedan":
var color = tokens[1];
vehicle = new Car(color);
break;
case "bus":
vehicle = new Bus("yellow");
break;
default:
throw new …
}
101. What’s wrong with switch ?
String[] tokens = ...
Vehicle vehicle;
switch(tokens[0]) {
case "car":
case "sedan":
var color = tokens[1];
vehicle = new Car(color);
break;
case "bus":
vehicle = new Bus("yellow");
break;
default:
throw new …
}
fallthrough
weird scope
initialization hidden
102. Fix the switch
Separate the cases with a comma + arrow syntax
String[] tokens = ...
Vehicle vehicle;
switch(tokens[0]) {
case "car", "sedan" -> {
var color = tokens[1];
vehicle = new Car(color);
}
case "bus" -> {
vehicle = new Bus("yellow");
}
default -> throw new …
}
103. Add a switch expression
A switch that can “return” a value
var tokens = ...
var vehicle = switch(tokens[0]) {
case "car", "sedan" -> {
var color = tokens[1];
...
}
case "bus" -> new Bus("yellow");
default -> throw new …
};
104. Exhaustive Switch
The switch expression requires a “default”
var tokens = ...
var vehicle = switch(tokens[0]) {
case "car", "sedan" -> {
var color = tokens[1];
...
}
case "bus" -> new Bus("yellow");
default -> throw new …
};
105. Exhaustive Switch (again)
For enums, default is not required if exhaustive
enum Kind { CAR, SEDAN, BUS }
var tokens = ...
var vehicle = switch(kind) {
case CAR, SEDAN -> {
var color = tokens[1];
...
}
case BUS -> new Bus("yellow");
};
106. Return a value from a block
And not return from the method
var tokens = ...
var vehicle = switch(tokens[0]) {
case "car", "sedan" -> {
var color = tokens[1];
??? new Car(color);
}
case "bus" -> new Bus("yellow");
default -> throw new …
};
107. Return a value from a block
And not return from the method
var tokens = ...
var vehicle = switch(tokens[0]) {
case "car", "sedan" -> {
var color = tokens[1];
break new Car(color);
}
case "bus" -> new Bus("yellow");
default -> throw new …
};
108. Hyphen keyword
Using ‘-’ to extend the number of keywords !
var tokens = ...
var vehicle = switch(tokens[0]) {
case "car", "sedan" -> {
var color = tokens[1];
break-with new Car(color);
}
case "bus" -> new Bus("yellow");
default -> throw new …
};
109. Switch enhancement
Retrofit old switch
– Arrow syntax and comma separated case values work for both switch
Introduce switch expression
– exhaustive
– default not needed for enums
110. Switch enhancement
Already in Java 12
– Under the flag --enable-preview
Not a preview feature in Java 13
– Uses break-with instead of break
117. Limitations
Only works if
– the format is a constant!
– the format has no dependency on java.util.Locale!
(double formatting)
In the work
– should work for JIT constant not only compiler constant
– Consider the Locale as a constant + deoptimisation
119. Example in Java
Java class initialization is lazy by default
=> so not issue here!
But static block initialization is the devil
Usually trigger other class initializations
=> applications are slooow to boot
120. Use Scala’s lazy keyword
class Utils {
public static final lazy Path HOME =
Path.of(System.getenv("HOME"));
}
Problem:
Scala uses the Double-checked Locking pattern
121. The Double-checked Pattern
The correct implementation disables further useful optimizations :(
class Utils {
private static volatile Path HOME;
public static Path getHome() {
var home = HOME; // volatile read
if (home == null) {
synchronized(Utils.class) {
home = HOME;
if (home == null) {
return HOME = Path.of(System.getenv("HOME"));
}
}
}
return home;
}
}
122. Constant Pool
A classfile has a dictionnary of all constants (constant pool), each
constant is transformed once to a runtime Java Object
#30: ...
#31: Utf8: "hello riviera dev"
#32: String: #31
#33: ...
class Utils {
public static void main(String[] args) {
//System.out.println("hello riviera dev");
ldc #32
...
}
}
123. Constant Dynamic
ConstandDynamic (Java 11) is a constant that can be computed dynamically
#28: Utf8: "Ljava/nio/file/Path;"
#29: Utf8: "HOME"
#30: NameAndType: #29:#28 // HOME Ljava/nio/file/Path;
#31: MethodHandle 6:#… // Utils.lazy_HOME_init ()Ljava/nio/file/Path;
#32: ConstantDynamic: 00:#30
BootstrapMethods:
00: #31
class Utils {
private static Path lazy_HOME_init() { return Path.of(System.getenv("HOME")); }
public static void main(String[] args) {
//System.out.println(??);
ldc #32
...
}
}
125. Compilation Strategies
A lazy static field
Loaded from the same class
●
Use ldc
Loaded from another class
●
Use getstatic ?
126. getstatic
Opcode getstatic need to be changed to recognize attribute DynamicValue
#30: NameAndType: #29:#28 // HOME Ljava/nio/file/Path;
#31: MethodHandle 6:#… // Utils.lazy_HOME_init ()Ljava/nio/file/Path;
#32: ConstantDynamic: 00:#30
#33: Field …:#30 // Utils.HOME Ljava/nio/file/Path;
BootstrapMethods:
00: #31
class Utils {
field: #30
DynamicValue: #32
private static Path lazy_HOME_init() { return Path.of(System.getenv("HOME")); }
public static void main(String[] args) {
//System.out.println(??);
getstatic #33
...
}
}
127. Lazy static : Java vs Scala
Scala (double-checked pattern)
– Guarantee singleton
– Perf issue: Volatile read + nullcheck
Java (getstatic + constant dynamic)
– Singleton after creation
●
need to be idempotent
– Plain static final read
●
constant for the VM
128. Lazy static final in Java
Scheduled to be introduced in Java 14
“lazy” can not be used on final instance field
130. Example in Java
Embedded code is unreadable
var html =
"<html>n" +
" <body style="width: 100vw">n" +
" <p>Hello World.</p>n" +
" </body>n" +
" <script>console.log("loadedn")</script>n" +
"</html>";
131. Example in Java
Embedded code has a lot of boilerplate
var html =
"<html>n" +
" <body style="width: 100vw">n" +
" <p>Hello World.</p>n" +
" </body>n" +
" <script>console.log("loadedn")</script>n" +
"</html>";
132. Borrow C# raw string
var html =
@"<html>
<body style=""width: 100vw"">
<p>Hello World.</p>
</body>
<script>console.log(""loadedn"")</script>
</html>";
but with a different delimiter
– C# needs to de-specialized quotes
– we can not embed C# easily in Java
133. Proposed Solution – Fat String
Use """ to start and end a fat strings
var html =
"""<html>
<body style="width: 100vw">
<p>Hello World.</p>
</body>
<script>console.log("loadedn")</script>
</html>""";
134. Examples
With pattern matching
var pattern = Pattern.compile("""""");
A multi-lines string
var s = """this is a long
multi-lines
of text""";
Embedded code
var s = """< a href="javascript: alert('hello')">""";
135. Fat/Raw String in Java
Was initially scheduled for Java 11
Was a real raw String (no escape of u….)
Using a variable number of backticks (`)
But early adopter reactions were “meeh”
Still in discussion
Raw ? Auto-alignment ?