Java Magazine JanFeb 2018



Comments



Description

INTERFACES IN DEPTH 90 | BOOKS ON JAVA 9 07JANUARY/FEBRUARY 2018 magazine REACTIVE By and for the Java community PROGRAMMING Handling large data streams eiciently 16 REACTIVE 32 RXJAVA— 61 REACTORS IN 69 CQRS: NOT PROGRAMMING REACTIVE SPRING 5.0 THE USUAL WITH JAX-RS LIBRARY FOR CRUD THE JVM ORACLE.COM/JAVAMAGAZINE //table of contents / COVER FEATURES 32 61 69 GOING REACTIVE REACTIVE SPRING COMMAND QUERY WITH ECLIPSE VERT.X By Josh Long RESPONSIBILITY AND RXJAVA Proceeding from fundamentals, SEGREGATION By Clement Escoier use the Spring Framework WITH JAVA and Julien Ponge to quickly build a reactive By Sebastian Daschner Building fast scalable systems application. Get around the limitations of with one of the most popular CRUD by using event streams 16 reactive Java libraries and an eventually consistent architecture. REACTIVE PROGRAMMING WITH JAX-RS By Mert Çalışkan Using an asynchronous approach and staging to develop responsive reactive apps OTHER FEATURES DEPARTMENTS 90 101 05 13 The Evolving Nature Fix This From the Editor User Groups of Java Interfaces By Simon Roberts and Mikalai Zaikin The decline of dynamic typing The Denver JUG By Michael Kölling Our latest quiz with questions that 07 114 Understanding multiple inheritance test intermediate and advanced Java Books Contact Us in Java knowledge of the language Reviews of Java 9 Modularity and Have a comment? Suggestion? Want to Java 9 for Programmers submit an article proposal? Here’s how. 10 Events Upcoming Java conferences and events COVER ART BY PEDRO MURTEIRA 02 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 The development. Richard Merchán Senior Designer RESOURCES Arianna Pucherelli Oracle Products Designer +1. your skills across all online platforms. EDITORIAL PUBLISHING Editor in Chief Publisher and Audience Development Andrew Binstock Director Managing Editor Karin Kinnear Claire Breen Audience Development Manager Copy Editors Jennifer Kurtz Karen Perkins. and should not be relied upon in making purchasing decisions.800. SUBSCRIPTION INFORMATION Subscriptions are complimentary for qualified individuals who complete the subscription form. Oracle and Java are registered trademarks of Oracle Corporation and/or its Claim your certification badge and validate affiliates. No part of this publication may be reprinted or otherwise reproduced without permission from the editors. please email the editors. or functionality. Java Magazine is published bimonthly and made available at no cost to qualified subscribers by Oracle. Other names may be trademarks of their respective owners. code. Oracle and/or its affiliates. WHETHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ORACLE BE LIABLE FOR ANY DAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN. editors.COM/JAVAMAGAZINE ///////////////////////////////// JANUARY/FEBRUARY 2018 . 500 Oracle Parkway. Leslie Steere Technical Reviewer ADVERTISING SALES Stephen Chin Sales Director Tom Cometa DESIGN Account Manager Senior Creative Director Mark Makinney Francisco G Delgadillo Mailing-List Rentals Design Director Contact your sales representative.com Display Your Oracle Certification Digital Badge PRIVACY Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer that your mailing address or email address not be included in this program. and may not be incorporated into any contract.283. Opinions ASSOCIATE PROFESSIONAL MASTER EXPERT SPECIALIST expressed by authors. JAVA MAGAZINE IS PROVIDED ON AN “AS IS” BASIS. MS OPL-3A. contact Customer Service. ORACLE EXPRESSLY DISCLAIMS ALL WARRANTIES. MAGAZINE CUSTOMER SERVICE You’ve Earned It [email protected]. CA 94065-1600.8674 (US/Canada) Jaime Ferrand Oracle Services Senior Publication Designer +1. It is intended for information purposes only.888. All Rights Reserved. and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Redwood City. The information is intended to outline our general product direction. Copyright © 2018. It is not a commitment to deliver any material. 03 ORACLE. release. and interviewees—even if they are Oracle employees—do not necessarily reflect the views of Oracle.0591 (US) Sheila Brennan Production Designer Kathy Cygnarowicz ARTICLE SUBMISSION If you are interested in submitting an article. AI. NoSQL. Oracle. and APIs • MySQL.com/code .oracle. Microservices.Register Now Oracle Code is BACK! | 1-Day. and Chatbots Coming to a city near you: developer. Free Event Explore the Latest Developer Trends: • DevOps. Containers. and Open Source Databases • Development Tools and Low Code Platforms • Open Source Technologies • Machine Learning. high-performance and battle-tested platform and infrastructure services for the most demanding I f you follow the rise and fall of programming languages—either from the comfort of an armchair.com dynamically typed Objective-C with Swift also cation. or a boolean at vari- emerged in the past decade—Go. happy to hyperkinetically try out all does not allow the use of types that are resolved Built for modern app dev. Speciically. for follows this trend. static and Rust—they’re all statically typed. Kotlin. For example. in JavaScript (a dynami. //from the editor / Java in the Cloud The Decline of Dynamic Typing Oracle Cloud delivers A feature once viewed as a convenience has become more troublesome than it’s worth. example. static typing.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . using var. The most conspicuous example is Static typing provides several important the recent set of updates to JavaScript (or more advantages. such as those found in Java. ous times in the same program. a keyboard. static typing refers to a type system that makes it possible to know the type of every data item and expression at compile Java apps. Because the compiler knows that i. Apple’s choice to replace piler can perform signiicant program verii- developer. Built for you. The irst advantage is that the com- Start here: accurately. force you to languages that were once dynamic have added declare the type when you deine the variable. Swift. types. or from time. Moreover.oracle. rather than a speciic type. ECMAScript). this means that the language Oracle Cloud. ensconced with your preferred tools As a quick refresher. kinds of new idioms—you will have noticed an at runtime. unmistakable trend in modern language design: cally typed language) a variable is declared by a preference for static typing. it can #developersrule PHOTOGRAPH BY BOB ADLER/THE VERBATIM AGENCY 05 ORACLE. but interested in other people’s choices. has been declared an integer. a number. In contrast. A variable Look at the major languages that have can hold a string. when PC guages. in popular languages in the mid- developer. In part. Say the vari. base? These problems are bear. and Ruby—run much more able in the small but extremely Andrew Binstock.com to understand code if types are that needed runtime support. which runs in large projects—was the pri. us for a long time. But this speed is a create TypeScript. it is unlikely guages don’t require. it is much easier ful enough to run languages developer. which in my 1990s (Python. and the cost The Best able and the methods that are that a spelling error by the devel. //from the editor / check that all places where i is this aspect is invaluable. a four-year window). of a variable? And if the latter. was used do expect or at least can through code in which the con. a bug is discovered. dynamic typing. with free trials. While those dynamically typed is running has signiicant over. performance becomes more important. which facilitated 06 ORACLE. The Oracle Developer Perl. or was it an intentional reuse languages will surely be with for Modern head that statically typed lan. First.oracle. tools were primitive then possible to tell exactly what and compile times were long. Likewise. Trials. tents of a variable can change But while dynamic languages static source code checkers are type is not anybody’s idea of fun. view is the one that has turned and PHP all appeared within the tide against dynamic lan. some 15 years later the have complete type information. so #developersrule you’re looking at. Stepping quick and easy development. a welcome step forward. who meant to store it in u. its superset of and more. hardware had become power- for readability. Downloads. Start here: respective JavaScript engines. Google and Microsoft into their Dynamic typing lourished Tutorials.com to jump-start your modern options. this how should you understand that many new languages will Cloud Dev is why many of the traditional other instances of i in the code. have retained considerable popu- much more capable when they The dynamic aspect also intro. This javamag_us@oracle. An exception to this problem—precisely as it appears @platypusguy cloud development skills might be JavaScript. comparatively recent advance JavaScript that added one princi- driven by massive investments by pal feature: types. At declared statically because it is the time. Resource available to it while the program oper. dynamic languages—Python. languages. JavaScript.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . Editor in Chief Gateway is the best place slowly than statically typed troublesome in the large. support an integer. embrace the model. A runtime that must determine the type of every vari- able i. which previously held an integer. much faster than many dynamic mary motivation for Microsoft to tutorials. For debugging. was larger. is maintainability.com A inal beneit. apparent as codebases grow formance. larity. Ruby. of maintenance rises steadily. duces a kind of uncertainty when cost of dynamic typing is more A second key beneit is per. now holds a string. downloads. documentation.oracle. one speciically on Java 9 modules and one on the larger language. ance between devising modules Some sites. Although you cer. the arrival of Java 9 has unleashed a wave of books examining and A explaining its new features.COM/JAVAMAGAZINE ///////////////////////////////// JANUARY/FEBRUARY 2018 . It’s a very By Sander Mak and Paul Bakker ing to provide the traditional bits readable guide. it of Java libraries. with proposition. especially those wres. With modules. The goal is to ind the bal- ries during the next few years. I look at two books. However. the Java 9 signiicantly changed how and Bakker’s new work. JAVA 9 MODULARITY modular JAR iles while continu. really apparent. The remaining that run on JVMs prior to this 180 pages are where the value is new release.” will likely ind incentive to minimum number of dependencies move to modules as quickly as pos. explanation of what modules are been more of a desirable goal than ticularly important for developers and how they work. //java books / Java 9 Books The wave of books for the new release is now arriving. In this installment. s with all previous major releases. These changes are par. who need to work chapters cover the anatomy and becomes a much more serious out their strategy for delivering use of modules in detail. impetus to get the design right in Java applications are built and The book opens with a detailed traditional JARs historically has delivered. This tension sible. Those sites will discover a is familiar to Java architects The introduction of modules in trove of useful information in Mak designing JARs. on external modules. The next few book columns will review important titles that you’ll want to be aware of. that naturally (that is. which are ways of architecting it is expected that most sites will modules so that they work together switch over to module-based bina. runtime without using modules. plenty of examples. conceptu- tling with so-called “classpath ally) it together while creating the hell. ideally. These pages start tainly can run apps on the Java 9 out covering modularity patterns. The irst four an imperative. The whole point of 07 ORACLE. 1.000-page volumes that present own code. erences. To get a sense of the yellow background. This choosing one or the other depends seen on Java 9 that has in-depth The authors tackle many book was explicitly recommended in large part on your personal pref. your eyes siderations presented in the rest of to come to market that includes is a full 52 pages that explore the will quickly tire of reading pale the book. The design portion includes with accompanying solutions.) the authors. In addition to the language use in containers. This will be particularly developing the code.COM/JAVAMAGAZINE ///////////////////////////////// JANUARY/FEBRUARY 2018 . extensive coverage of Java 9. how modules blue text or squinting at bright Taken together. the section on modules brightly colored code. The inal sections have pointers By Paul Deitel and Harvey Deitel initial design of an ATM machine JDBC. pal APIs. and tips on writing idiomatic modules. prehensive language tutorials example. after which they explore JAVA 9 FOR intensive with numerous examples. starting with limited Java 9’s most important fea. use of color highlighting in the migration to the new runtime and This book is the irst of the com. putting together the object. fully agree with their assessment. this is a com- useful to sites that are planning through this project is an excellent plete presentation. and that is the excessive full scenario. the new REPL aspects of the problem: splitting at Devoxx in November by mem. Each chapter for library designers and a handy all the way through to comple. who drill into how They then move into technical —Andrew Binstock The Deitels’ book is notable for to make best use of it both as problems such as encapsulating its hands-on orientation: it is code. an abridged version is available. the entire language and its princi. caveats for dangers. building modules speciically for PROGRAMMERS It even includes a full project (com. and how to use them in your green comments on a canary- represent a comprehensive over. In other words. It was one of our most dencies intelligently to get rid of how to program in Java. teaching tool. (4TH EDITION) prising 77 pages) that goes from proper. handle that. Both popular articles in 2017. the as Maven and Gradle. The writ. and I been released for Java 9. classpath conlicts and enable details (such as how classloaders entrants are ine works. it competes tions. and bers of the core Java team. includes self-review exercises. volume. to adopt modules at some future education quite apart from the use I have only one gripe with this point and want to understand the of Java. such tion. aggregating modules. and incrementally tices. it competes with other work. low-level previously in this column. the book covers JavaFX. work) are explained on the ly. (Note: Core Java has not introduced in Java 9. about good programming prac- run Java 9 without migrating to oriented design. although gogical beneits are not lost on creating new modules as facades. Working Java. all these topics context. coverage of JShell. which I’ve reviewed magazine. introduction to the basic Uniied explanations are sprinkled with Wedged into all this goodness Modeling Language (UML) dia. Even if you’re a fan of then slowly implementing the con. a programming aid and as a resources. tures receive rich coverage. For code. and JPA. for modules. //java books / modularity is to manage depen. reminders is a lengthy discussion of how to grams. you’ll have a very ine ing is clear and easy to understand. reader to know much more than Core Java. see the lightly edited excerpt book that does an excellent job of and the authors do not expect the with Cay Horstmann’s excellent from this section that ran in this presenting Java 9. In this need for modules. and This is the irst book I’ve delivery of modestly sized binaries. For example. But if you can view of Java 9 modularity. section on coniguring tools. Its peda- modules. —AB 08 ORACLE. hands-on nature of the explana. Java: The Complete OCA Java SE 8 Rapid Modernization 7th Edition Reference. and up-to-date coverage of Java available. Java: A Beginner’s Guide. Venkat this book gets you started Updated for Java SE 9. www. this book Get complete coverage of all Adopt a high-performance programming in Java right away. shows how to develop. Electronic practice exam modernization strategy. compile. questions are included. Your Destination for Oracle and Java Expertise Written by leading experts in Java. Bert Bates G.OraclePressBooks. complete. Oracle Press books offer the most definitive.com • @OraclePress . Available in print and eBook formats. objectives for Exam 1Z0-808. Herb Schildt Kathy Sierra. enterprise Java application debug. Programmer I Exam Guide of Java Herb Schildt 10th Edition (Exam 1Z0-808) Applications Revised to cover Java SE 9. and run Java programs. while skiing and net- working take place in Lech. gathering 8. build projects with them. EXPO JANUARY 25–26. block- Performance Tuning with jPDM. GEORGIA ence dedicated to software engi. //events / SnowCamp DevConf. dubbed “unconfer- ence.” and tracks & Practices with Kubernetes/OpenShift and Istio. FEBRUARY 21–23 two days of skiing.000 DevNexus AgentConf is two days of talks and participants for a week-long. conference and associated events. HACKATHON ers on the ski slopes. and workshops will that focuses on Java. WORKSHOPS JANUARY 26–28 JANUARY 25–26. SPEAKER SESSIONS OAKLAND./FLICKR 10 ORACLE. CONFERENCE BRNO.” and “Practical JVM connects industry experts from serverless development. and whose teams and JavaScript. Speaker sessions are hosted at Spielboden in Dornbirn.” ofers a unique opportunity DeveloperWeek to socialize with peers and speak. WORKSHOPS FEBRUARY 5–7. and Revolution of Code. Several DevOps. Node.cz is a free. ESQ. CALIFORNIA JANUARY 27–28. The theme for 2018 is “Industrial Scheduled sessions this year include “Java Microservices Patterns ReactJS. cloud.” “Pragmatic similar technologies. three-day. ReactNative. technology-neutral programming ATLANTA. and the confer- French (the majority) and English. AUSTRIA conference series. ference held in the French Alps presentations. web. All talks. ence can be attended online. FEBRUARY 5. THE CZECH REPUBLIC JANUARY 27. tracks are usually devoted specii- ture. technologies. focusing on JavaScript. with a mix of sessions in cally to Java EE.cz JANUARY 24. The last day. The event include artiicial intelligence. FRANCE open source developer and SnowCamp is a developer con. It is a confer. CONFERENCE AgentConf FEBRUARY 6–7. DevNexus is an international open source developer conference. GRENOBLE. SOCIAL EVENT DevConf. neering.COM/JAVAMAGAZINE ///////////////////////////////// JANUARY/FEBRUARY 2018 . Microservices with Java EE and WildFly Swarm. SKIING/ DeveloperWeek promises the NETWORKING world’s largest developer expo and DORNBIRN AND LECH. FEBRUARY 3–4. and software architec. APIs and microservices. be conducted in English. DevOps conference.” around the world who use these chain. PHOTOGRAPH BY NDINHTRAN. ENGLAND case studies. THE NETHERLANDS The annual Scandinavian Java and security. JSConf Iceland Handling in Java. GERMANY ZÜRICH.” Topics include internationally renowned and JANUARY 30–31. JSConf will take place at Harpa. soft. Scheduled presentations include PHOTOGRAPH BY BRIYYZ/FLICKR 11 ORACLE. DevOps. MARCH 1–2 thinking and complexity theory. front-end for Complex Domains. This conference features lectures “Event-Driven Microservices with Conference ture two tracks of educational on subjects such as core Java Axon Framework” (Java experi.COM/JAVAMAGAZINE ///////////////////////////////// JANUARY/FEBRUARY 2018 . such as Scala and Clojure. //events / This event promises four days of QCon London in-depth professional training MARCH 5–7. one of Reykjavik’s most distin. TUTORIALS speakers from around the world. FEBRUARY 25–26. cloud computing. and much more. IoT. local speakers. systems end and web development. and draws Domain-Driven Design Europe Jfokus Autonomous. Immutability” and “A Hitchhiker’s This software development and developer conference encom. Sessions include FEBRUARY 1–2. visualization. and Netlix cloud Database Architecture. Scheduled workshops include O’Reilly Software Architecture guished landmarks. BRÜHL. CONFERENCE STOCKHOLM. SWITZERLAND The theme for the 16th annual Voxxed Days Zürich shares the gathering of embedded system Devoxx philosophy that con- developers is “Embedded Goes tent comes irst. testing and refactor. MARCH 8–9. frameworks. GERMANY tion. Docker engineer Anil Microservices. and sions include “High-performance more. SWEDEN ware engineering. WORKSHOPS FEBRUARY 5–7 IoT. and the latest trends QCon conferences feature tracks in technologies.” year include Java Champion “Pragmatic Event-driven Trisha Gee. front. and collabora. cloud. autonomous systems. and techniques. real-world LONDON. and safety “The Power and Practicality of AMSTERDAM.” sis. Guide to the Functional Exception engineering event spans analy.” platform engineer Allen Wang. Embedded World Voxxed Days Zürich FEBRUARY 27–MARCH 1 MARCH 8 NUREMBERG. mobile. ICELAND JavaLand architecture. modeling and design. and fea. WORKSHOPS ture fundamentals. Scheduled ses. and JVM languages REYKJAVIK.” AND CONFERENCE followed by evening parties development. TRAINING JavaScript talks by more than 30 and JVM languages. micro- ence required) and “Techniques FEBRUARY 26–28. services architecture. Conirmed speakers this JavaScript Web App Architecture. related to web development. NEW YORK. NEW YORK and socializing.” and “Evolving Madhavapeddy. passes Java SE and Java EE. MARCH 13–15 ing. CONFERENCE that covers software architec. LONDON. //events / “The Java 9 Module System Java Day Istanbul Beyond the Basics. The conference experts. sessions. Topics include modern event for developers interested in run by the Bulgarian Java User approaches in development of big data. SPAIN talks on Java. Massachusetts There’s also a two-in-one confer. Boston. tions in application development Voxxed Days is heading down using Java. JEEConf. mobile. containers and infra. The event is ming languages. and key. WeAreDevelopers APRIL 10.” and “Next-Generation ISTANBUL.NET technolo. tures. expects more than 8. focuses J On The Beach (JOTB) is an inter.000 partici. APRIL 4. web. and exhibitions.” efective international community- opers to learn about the latest pro- driven software conferences in gramming technologies. highly loaded. JEEConf MAY 29–30 The event will feature insights MAY 18–19 J On The Beach SOFIA. the largest Java confer. JAX DevOps Turkey. and innovations and new direc. AUSTRIA MARCH 8. Bangalore. enterprise systems with Java ment. MELBOURNE. able. gies. pants and more than 150 speakers MAY 17. AUSTRALIA ics. industry leaders. APRIL 17. scal. panel discussions. Singapore ence package that provides free for keynotes. Experience cloud This event for software experts Java. MAY 2–3 ment. India speakers and industry experts. JAX Finance. and other live. jPrime under to Melbourne. New York. and data visualization. sessions. and other APRIL 10–11. mobile and web programming. real-world architec. development technology in the Code Lounge with workshops highlights the latest technologies DevOps. embedded and IoT develop- Voxxed Days Melbourne front-end and back-end develop. and program. Hyderabad. MALAGA. blockchain. data and machine learning. practices. The program includes talks and sessions on distributed. JVM and . functional programming. JVM languages. TURKEY Oracle Code Events Web Components with Java Java Day Istanbul is one of the most Oracle Code is a free event for devel- Vaadin Flow. India notes will be led by international gress in Europe. national workshop and conference and best practices. BULGARIA into cloud. WORKSHOPS Java User Group. and more.” “Securing MAY 5 JAX-RS.COM/JAVAMAGAZINE ///////////////////////////////// JANUARY/FEBRUARY 2018 . ence in Eastern Europe. and increased MAY 16–18 quality in delivery. UKRAINE MAY 23–25 jPrime will feature two days of structure. ENGLAND the newest technologies. including and hands-on labs. hackathons. robot. access to a parallel conference. interactive experiences and demos. cloud. opment. Los Angeles. big data. security. workshops. KIEV. CONFERENCE helps developers network and learn developers in keynotes. California in functionality. and methodologies for accelerated delivery cycles. Learn from technical APRIL 9 AND 12. and agile. New York workshops. artiicial intelligence. contests. Group and provides opportunities 12 ORACLE. the modern web. on practical experience and devel. Billed as the largest developer con. More than 60 VIENNA. organized by the Istanbul and trends. Australia. faster changes WeAreDevelopers World Congress FEBRUARY 27. //events / //user groups / for hacking and networking. For ive days. the DJUG JavaOne has grown to more than O’Reilly Fluent OCTOBER 28–NOVEMBER 1 2. venue for the exchange of ideas. is designed to appeal to applica. and all Denver Java is devoted to practical train. Tutorials DJUG meetings are held on the second Wednesday of architects. . appli. Java Champion Simon training credits. area. more.COM/JAVAMAGAZINE ///////////////////////////////// JANUARY/FEBRUARY 2018 . TRAINING SAN FRANCISCO.NET. Since then. software architec. ing about Java. DevOps. speaker presentation. TUTORIALS Whether you are a seasoned the use of Java. trends in programming. Door EclipseCon France and a description of your event prizes and food and beverages for the networking sessions JUNE 13–14 at least 90 days in advance at are provided with the generous help of sponsors. 13 ORACLE. machine learning. like to see included in this calen. APIs. hack-proof ence for system engineers. mobile. Presentation topics from the past year include with O’Reilly’s Velocity confer. and applications. CALIFORNIA JavaOne is the ultimate source of Java developers in the Denver. Are you hosting an upcoming security. educate users of Java technology. and 1995 as an opportunity for DevOps. and DevOps Java conference that you would Organized and run by volunteers. and UI/UX designers. Other Follow the DJUG’s activities by joining its meetup group EclipseCon France is the Eclipse ways to reach us appear on the or visiting its website. France qualiies for French the Java language. the enthusiasts are encouraged to join.com. and Devoxx. IoT. and emerging technologies. Contact the DJUG on Twitter with pro- Foundation’s event for the entire last page of this issue. This event developers gather to talk about Fluf Just Stuf Software Symposium. and interactive guages. User Group (DJUG) meet- The biggest tech conference in embedded systems. The O’Reilly Fluent conference technical information and learn. and on software-related products. CALIFORNIA Its goal is to promote JUNE 12–14. applets. posals for talks. European Eclipse community. cation developers. development tools. This year. LATVIA communities. Project Jigsaw.500 members. and lightning talks. FRANCE javamag_us@oracle. DJUG members have ing for building sites and apps world’s largest collection of Java access to conference discounts for events such as the No for the modern web. Membership in the DJUG is free. The conference program includes THE DENVER JUG Riga Dev Days technical sessions on current MAY 29–31 topics pertinent to developer The irst Denver Java RIGA. Ritter is scheduled to speak. door dar? Please send us a link prizes. on numerous related Java and JVM every month. such as modeling. JUNE 11–12. 120 attendees. UberConf. cloud. as well as engineers. and create a community for SAN JOSE. and the typical meeting has between 70 and The conference will be collocated topics are ofered. provide a AND CONFERENCE coder or a new Java programmer. microservices. TOULOUSE. typical format: networking time. developers. the meetings follow a professionals. and data science. Meeting attendees also have the opportunity to win discounts tion. data analytics ing was held in November the Baltic States covers Java. and then more networking at a local restaurant. Colorado. Attendance at EclipseCon technical discussion of ture. all aspects of Java and JVM lan. web. . It might seem that reactive programming is a design that would lead naturally to microservice implementation. and it anticipates handling the number of events associated with big data—millions to billions of incoming events. a subscription-based notiication system. We follow that up by look- ing at the reactive capabilities built into the most recent release of Spring 5. //reactive programming / REACTIVE PROGRAMMING WITH JAX-RS 16 USING VERT. called Command Query Responsibility Segregation. we provide an overview of reactive development (page 16) and then do a deep dive into RxJava (page 32). ART BY PEDRO MURTEIRA 15 ORACLE. though. This aspect in particular is what makes the reactive model diferent from its familiar forebear. Central to the concept. one of the leading libraries for developing reactive applications on the JVM. The scalability here refers to the ability to scale horizontally quickly. The beneit is a loosely coupled implementation that is scalable and tends to isolate failures. and an asynchronous execution of the event-driven tasks. or CQRS (page 69).COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .X AND RXJAVA 32 What Is Reactive REACTIVE SPRING 5. In practice. And indeed it is. we examine a slightly diferent model for develop- ing CRUD applications. and works with the event source to manage the number of events to be processed. Finally. which while not reactive per se implements an approach that overlaps with reactive programming. can process or ignore those events. is a model of computing that is alerted to certain kinds of events.0 61 CQRS 69 Programming? R eactive programming is a term that means slightly diferent things to diferent people. In this issue. the event loop in GUI development. this model rests on several technologies: a message-passing framework.0 (page 61). and easily scalable—and. It says an application should be responsive. And the data stream that I mentioned is the actual observ- able that will be observed. resilient. observers are functions that are executed when an event is emitted. Having an application that is truly responsive is the foundational goal. elastic (that is. and this thread 16 ORACLE. events are pushed asynchro- nously so the observers can process them. In this article. loosely coupled. capable of being reactive. I explain how reactive programming can be applied by using the latest version of JAX-RS from Java EE 8 and by using Java 8 features under the hood. Based on data that lows continuously. //reactive programming / Reactive Programming with JAX-RS Using an async approach and staging to develop responsive reactive apps MERT ÇALIŞKAN eactive programming sounds like the name of an emerging programming paradigm at irst. the other objects are notiied and updated accordingly. scalable). Therefore.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . and message-driven. Suppose you have an application that heavily depends on one big thread to handle user requests. R but it refers to a programming technique that ofers an event-driven approach for handling asynchronous streams of data. and Java has kept the pace up in its latest releases. reactive systems react to the data by executing a series of events. The Reactive Manifesto The Reactive Manifesto lists four fundamental aspects an application must have in order to be more lexible. which can be deined as fol- lows: when there is a change of state in one object. Reactive programming follows the Observer design pattern. instead of polling events for the changes. Nearly all languages and frameworks have adopted this programming approach in their ecosystems. In this example. therefore. An example for this implementation is shown in Listing 1. you need to make it scalable and resilient. only a message-driven architecture can enable a scalable. Resilience occurs when an application exhibits features such as auto-recovery and self-healing. Response response = ClientBuilder. after closer examination you will see that cation itself will not be able to be as responsive as it’s fairly straightforward. Listing 1.1 Reactive Client API Let’s look at how reactive programming can be used in Java EE 8 applications. resilient.request() 17 ORACLE. because responsiveness is possible only with both scalability and resilience. Reactive programming has started to be baked into the bits of the Java 8 and Java EE 8 releases. CompletableFuture. The default invoker implementation provided by JAX-RS is synchronous.1 introduced a new way of creating a REST client with support for reactive pro- gramming. and responsive application. When the applica- The reactive implementation might tion gets more requests than it can handle. To follow along. but thread will start to be a bottleneck and the appli. you’ll need familiarity with the basic Java EE APIs. //reactive programming / typically sends responses back to its originating requesters after doing its work. JAX-RS 2.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . JAX-RS 2.target("http://localhost:8080/service-url") .newClient() . To have the application be respon- sive. which means the client that is created will make a blocking call to the server endpoint. The Java language introduced concepts such as CompletionStage and its implementa- tion. it was before. In most devel- opers’ experience. this look more complicated at first glance. and Java EE started to employ these features in speciications such as the Reactive Client API of JAX-RS. newClient() . As of version 2. CompletionStage<Response> response = ClientBuilder.1 ofers a reactive way to overcome these problems with the new JAX-RS Reactive Client API for building the client.request() 18 ORACLE. It’s as simple as invoking the rx() method while building the client. JAX-RS provides support for creating an asynchronous invoker on the client API by just invoking the async() method. Both of these implementation approaches are suitable for asynchronous programming. JAX-RS 2. or registering a callback that would be invoked when the HTTP response is available.get().core.ws. but things usually get complicated when you want to nest callbacks or you want to add conditional cases in those asynchronous execution lows. Future<Response> response = ClientBuilder.rs .get(). //reactive programming / .COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .target("http://localhost:8080/service-url") .Response. This would either result in polling the response.request() .0. with a call to future. In Listing 3.target("http://localhost:8080/service-url") . which enables the switch from sync to async invoker by this simple invocation.async() .newClient() . as shown in Listing 2. Using an asynchronous invoker on the client returns an instance of Future with type javax. Listing 3. the rx() method returns the reactive invoker that exists on the client’s run- time and the client returns a response of type CompletionStage.rx(). Listing 2.get(). and it represents a computation that can be a stage within a larger computation. as its name implies. Location Service Forecast Service Temperature Service Figure 1. I will make another call to another end- point with that location data to get a temperature value.thenAcceptAsync(res -> { Temperature t = res. Adding Reactive Goodness to a REST Endpoint The reactive approach is not limited to the client side in JAX-RS.rx() . it’s also possible to leverage it on the server side. //reactive programming / . I can just invoke thenAcceptAsync(). response. I will irst create a simple scenario where I can query a list of locations from one endpoint. Interaction between endpoints 19 ORACLE. For each location. CompletionStage<T> is a new interface introduced in Java 8.class). To demonstrate this.get(). //do stuff with t }). The interaction of the endpoints would be as shown in Figure 1. After getting a response instance.readEntity(Temperature. It’s the only reactive portion of Java 8 that made it into the JAX-RS. where I can provide the code snippet that would be executed asynchronously when the response becomes available. such as shown in Listing 4. Listing 4.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . public Location() {} public Location(String name) { this. which wraps the Temperature and Location classes. // getters & setters } public class Location { String name. private Temperature temperature. Listing 5.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . private String scale. public Forecast(Location location) { 20 ORACLE. //reactive programming / First. public class Temperature { private Double temperature. I simply deine the domain model and then I deine the services for each domain model. } // getters & setters } public class Forecast { private Location location.name = name. Listing 5 deines the Forecast class. //reactive programming / this.location = location; } public Forecast setTemperature( final Temperature temperature) { this.temperature = temperature; return this; } // getters } For wrapping a list of forecasts, the ServiceResponse class is implemented in Listing 6. Listing 6. public class ServiceResponse { private long processingTime; private List<Forecast> forecasts = new ArrayList<>(); public void setProcessingTime(long processingTime) { this.processingTime = processingTime; } public ServiceResponse forecasts( List<Forecast> forecasts) { this.forecasts = forecasts; return this; } // getters 21 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 //reactive programming / } LocationResource, which is shown in Listing 7, deines three sample locations returned with the path /location. Listing 7. @Path("/location") public class LocationResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response getLocations() { List<Location> locations = new ArrayList<>(); locations.add(new Location("London")); locations.add(new Location("Istanbul")); locations.add(new Location("Prague")); return Response.ok( new GenericEntity<List<Location>>(locations){}) .build(); } } TemperatureResource, shown in Listing 8, returns a randomly generated temperature value between 30 and 50 for a given location. A delay of 500 ms is added within the implementation to simulate the sensor reading. Listing 8. @Path("/temperature") public class TemperatureResource { 22 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 //reactive programming / @GET @Path("/{city}") @Produces(MediaType.APPLICATION_JSON) public Response getAverageTemperature( @PathParam("city") String cityName) { Temperature temperature = new Temperature(); temperature.setTemperature( (double) (new Random().nextInt(20)+30)); temperature.setScale("Celsius"); try { Thread.sleep(500); } catch (InterruptedException ignored) {} return Response.ok(temperature).build(); } } I will irst show the implementation for the synchronous ForecastResource (shown in Listing 9), which irst fetches all locations. Then, for each location, it invokes the temperature service to retrieve the Celsius value. Listing 9. @Path("/forecast") public class ForecastResource { @Uri("location") private WebTarget locationTarget; @Uri("temperature/{city}") 23 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 24 ORACLE.resolveTemplate("city".getForecasts().setTemperature(temperature)).build().request() .get(Temperature. long endTime = System.getName()) . } } When the forecast endpoint is requested as /forecast. @GET @Produces(MediaType.APPLICATION_JSON) public Response getLocationsWithTemperature() { long startTime = System. }).startTime).currentTimeMillis(). ServiceResponse response = new ServiceResponse(). response. location. return Response.currentTimeMillis().add( new Forecast(location) . //reactive programming / private WebTarget temperatureTarget.request() . response.get(new GenericType<List<Location>>() {}). Notice that the processing time of the request took 1.forEach(location -> { Temperature temperature = temperatureTarget . which makes sense because request- ing temperature values for three diferent locations synchronously would add up to 1.setProcessingTime(endTime .533 ms.class).COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .ok(response). locations. you should see output similar to Listing 10.500 ms. List<Location> locations = locationTarget. "temperature": 46 } } ]. "temperature": { "scale": "Celsius". { "location": { "name": "Istanbul" }. 25 ORACLE. { "location": { "name": "Prague" }. "temperature": 38 } }. "temperature": { "scale": "Celsius". "temperature": 33 } }.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . { "forecasts": [ { "location": { "name": "London" }. //reactive programming / Listing 10. "temperature": { "scale": "Celsius". @GET @Produces(MediaType.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .currentTimeMillis().rx() . which deines a reactive version of this forecast service. @Uri("temperature/{city}") private WebTarget temperatureTarget. Listing 11.get(new GenericType<List<Location>>() {}). This can deinitely enhance the synchronous low shown earlier. //reactive programming / "processingTime": 1533 } So far. where a call for each location could be done in parallel after getting all the locations. so good. // Create a stage on retrieving locations CompletionStage<List<Location>> locationCS = locationTarget.request() . @Path("/reactiveForecast") public class ForecastReactiveResource { @Uri("location") private WebTarget locationTarget. Now it’s time to introduce reactive programming on the server side. This is done in Listing 11.APPLICATION_JSON) public void getLocationsWithTemperature( @Suspended final AsyncResponse async) { long startTime = System. 26 ORACLE. thenCombine(tempCS. 27 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .thenCompose(locations -> { // Create a stage for retrieving forecasts // as a list of completion stages List<CompletionStage<Forecast>> forecastList = // Stream locations and process each // location individually locations.completedFuture( new Forecast(location)) . //reactive programming / // By composing another stage on the location stage // created above.rx() .stream().get(Temperature.request() .map(location -> { // Create a stage for fetching the // temperature value just for one city // given by its name final CompletionStage<Temperature> tempCS = temperatureTarget . // Then create a completable future that // contains an instance of forecast // with location and temperature values return CompletableFuture.getName()) . location. collect the list of forecasts // as in one big completion stage final CompletionStage<List<Forecast>> forecastCS = locationCS.class).resolveTemplate("city". // Return a final completable future instance // when all provided completable futures are // completed return CompletableFuture.collect(Collectors. // which contains the whole list of forecasts // along with the processing time. } } 28 ORACLE.thenCombine(forecastCS.collect(Collectors. }). ServiceResponse::forecasts) .currentTimeMillis() . }).map(CompletionStage::toCompletableFuture) . async. // Create a completed future of it and combine to // forecastCS in order to retrieve the forecasts // and set into service response CompletableFuture.setProcessingTime( System. //reactive programming / Forecast::setTemperature). throwable) -> { response.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .size()])) .toList())).thenApply(v -> forecastList.resume(response).allOf( forecastList.toArray( new CompletableFuture[forecastList.map(CompletableFuture::join) .startTime).stream() .whenCompleteAsync((response.toList()).completedFuture( new ServiceResponse()) . // Create an instance of ServiceResponse. }). completedFuture() by providing a newly created instance of Forecast as the parameter. In order to overcome this problem. The response from the service is an instance of the ServiceResponse class. As a last step of streaming on locations. Execution of this step returns the big completable future instance when all pro- vided completable futures are completed. I will ultimately create the response of the service call by using only forecastCS. Server Sent Events (SSEs) can also be used to partially send 29 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . and that enables me to pass the name of the city to the builder as a parameter. I irst create a client invocation on the location services with the help of the JAX-RS Reactive Client API. I use the resolveTemplate() method here to build a client. and it helps to create a reactive invoker simply by use of the rx() method. the client side will be blocked until the server sends the response back to the requester. Let’s continue by collecting the forecasts as a list of completion stages as deined in the forecastList variable. Reactive programming is more than enhancing but after closer examination you will the implementation from synchronous to asynchronous. it also eases development with concepts such as Within the ForecastReactiveResource nesting stages. They will be stored in one big completion stage. //reactive programming / The reactive implementation might look more complicated at irst glance. I combine this future with the tempCS stage so that I have the temperature value for the iterated locations. The CompletableFuture. As I mentioned previously. Of course. this is an addition to Java EE 8. I stream on the loca- tions and then create the tempCS variable by again using the JAX-RS Reactive Client API. Now I compose another stage based on location to collect the list of forecasts. so I create a com- pleted future for that as well. I do a call to CompletableFuture.allOf() method in Listing 11 transforms the list of completion stages to forecastCS. To create the completion stages for each forecast. as a list of forecasts. this reactive programming makes only the server side execute asynchronously. implementation. see that it’s fairly straightforward. which will invoke the temperature service with city name. and then I combine the forecastCS completion stage with the list of forecasts and calculate the response time of the service. named forecastCS. The output of ForecastReactiveResource will be something similar to Listing 12. the processing time is 515 ms. "temperature": 49 } }. "temperature": { "scale": "Celsius". As shown in the output. which is the ideal execution time for retrieving a temperature value for one location. { "location": { "name": "Prague" }. "temperature": { 30 ORACLE. "temperature": 32 } }. "temperature": { "scale": "Celsius". { "location": { "name": "Istanbul" }. the temperature values can be pushed to the client one by one.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . { "forecasts": [ { "location": { "name": "London" }. //reactive programming / the response once it’s available so that for each location. Listing 12. and he works as a developer on the Payara Server inside the Payara Foundation. I irst showed the synchronous way to retrieve the forecast information by choreographing location and temperature services. </article> Mert Çalişkan (@mertcal) is a Java Champion and a coauthor of PrimeFaces Cookbook (Packt Publishing. 31 ORACLE. "processingTime": 515 } Conclusion Throughout the examples in this article. 2013) and Beginning Spring (Wiley Publications. "temperature": 45 } } ]. 2015). He currently is working on his latest book. The more it is adopted. the power of asynchronous pro- cessing is unleashed with the help of reactive-style programming. Java EE 8 Microservices.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . it also eases development with concepts such as nesting stages. When you leverage the use of the JAX-RS Reactive Client API of Java EE 8 and classes such as CompletionStage and CompletableFuture shipping with Java 8. Then I moved on to the reactive approach in order to have the asynchronous processing occur between service calls. Reactive programming is more than enhancing the implementation from a synchro- nous to an asynchronous model. //reactive programming / "scale": "Celsius". the easier it will be to handle complex scenarios in parallel programming. As developers painfully learned. The recent reactive renaissance is mainly due to the dif- iculties of building robust distributed systems. Its exten- sive ecosystem provides everything you need to build responsive. It was designed from the start with a reactive design and asynchrony in mind. But using that deinition.x is also about freedom. distributed. and they fail for many reasons such as capacity issues.x combines an asynchronous execution model and a reactive implementation to let you build applications that can handle uncertain and ever- evolving development needs.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . with the rise of distributed systems. network outages. you are in charge. clicks. the Reactive Manifesto deined reactive systems as distributed systems with the following characteristics: JULIEN PONGE PHOTOGRAPH BY MATT BOSTOCK/GETTY IMAGES ■■ Message-driven: They use asynchronous message passing to communicate. commands. This article describes how Vert. and so on. What Does It Mean to Be Reactive? JULIEN PONGE Let’s start from the beginning: what does reactive actually mean? The Oxford English Dictionary deines reactive as “showing a response to a stimulus. a few years ago.x is a toolkit for implementing reactive and distributed systems on top of the JVM. scalable apps with one of the most popular reactive libraries CLEMENT ESCOFFIER E clipse Vert. hardware problems. Software is designed to react to user demands such as input. In response. It does not tell you how to shape your system. and bugs. Vert. //reactive programming / Going Reactive with Eclipse Vert. However.x and RxJava Building responsive. distributed systems are diicult. by extension. reactive software can be deined as software that reacts to stimuli.” So. and interactive applications. software has been reactive since the early age of computers. 32 ORACLE. applications started reacting to messages sent by peers and by failure events. you are handling streams of data in which data lows. You observe these streams and react when new data is available. this approach is particularly ineicient. the producer does not send too much data on the stream. coroutines. the traditional threading model (one thread per request) tends to create memory and CPU hogs. Several development models have emerged to make the development of asynchronous applications easier. the consumer notiies the producer of its current capacity. Taming the asynchronous beast is particularly dii- cult from the developer standpoint. or RX) is an asyn- chronous programming paradigm focused on the manipulation of data streams. Dropping incoming data is also a solu- tion. //reactive programming / ■■ Elastic: They stay responsive under varying workloads. and your system auto- adapts to its capacity without burning. It deines an asynchronous and nonblocking back-pressure protocol. In addition. and reactive programming. While reactive systems are described as “distributed systems done right. So. This architectural style promotes a new way to build distributed systems. What happens if you receive too many messages and you can’t process them in time? You could put a bufer between the source and the han- dler. infusing asynchrony into the core of these systems. but it would help only with handling small bumps. most applications have been developed using a synchronous execution model and 33 ORACLE. Why Do Reactive Systems Matter? Why did reactive programming become so prevalent in the past few years? For a very long time. but that is not always acceptable.” they can be diicult to build. ■■ Resilient: They stay responsive in the face of failure. you need a way to control the pace. In this low of control. and. This article focuses on the latter. ibers. ■■ Responsive: They respond in a timely manner. Reactive programming (and its main derivative. including actors. when dealing with asynchronous code. When using reactive program- ming. Reactive eXtensions. Ultimately. This is what the reactive streams speciication proposes.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . It provides an API to compose asynchronous and event-driven applications. But data streams have an inherent law. But. we present how Vert. Therefore. so the application waits for a response before it can continue its execution. To enable concurrency. In the rest of this article. the promise made by reac- tive systems is a perfect match. As a result. and now it’s time to catch up. For years. a single thread can handle several interleaved tasks. the code has to protect itself from concurrent access to its state. however. This is what Eclipse Vert.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . because switching between threads requires CPU cycles. the application relies on multithreading and increases the number of threads. the asynchronous nature of systems has been ignored. Because of the synchronous nature of application code. First.x ofers. where applications are massively distributed and interconnected and they must handle continuously growing traic. tion made to provide ease of comprehen- sion. //reactive programming / most APIs have been designed to follow this approach. it invokes a remote service using nonblocking I/O and will be notiied when the result is available). Thus.x combines both to give you superpowers. threads are expensive in terms of memory and—often overlooked—in CPU time. in a world of cloud and containers. However. such as remote invocations or access to the ile system. But. asynchronous execution model and a development Synchronous processing is a simpliica. 34 ORACLE. these I/O operations are designed to be blocking. Implementing reactive systems requires However. computer systems and two shifts: an execution shift to use an distribution systems are asynchronous. implementing reactive systems requires two shifts: an execution shift to use an asynchronous execution model and a development shift to write asyn- chronous APIs and applications. the same thread can switch to another task. Traditional development and execution paradigms are not able to exploit this new model. a more eicient model is needed. The asynchronous execution model promotes a task-based concurrency in which a task releases the thread when it cannot make progress anymore (for instance. Second. threads are expensive. Many modern applications are relying on I/O operations. shift to write asynchronous APIs and applications. //reactive programming / RxJava: The Reactive Programming Toolbox for Java Let’s focus on reactive programming—a development model for writing asynchronous code. When using reactive programming, the code manipulates streams of data. The data is gener- ated by publishers. The data lows between a publisher and consumers, which process the data. Consumers observing a data stream are notiied when a new item is available, when the stream completes, and when an error is caught. To avoid overloading consumers, a back-pressure pro- tocol is required to control the amount of data lowing in the stream. This is generally handled transparently by the reactive framework. There are several implementations of the reactive programming paradigm. RxJava is a straightforward implementation of reactive extensions (RX) for the Java programming lan- guage. It is a popular library for reactive programming that can be used to develop applications in networked data processing, graphical user interfaces with JavaFX, and Android apps. RxJava is the principal toolkit for reactive libraries in Java, and it provides ive data types to describe data publishers depending on the types of data streams, as shown in Table 1. These types represent data publishers and convey data processed by consumers observ- ing them. Depending on the number of items lowing in the stream, the type is diferent. For streams with a bounded or unbounded sequence of items, the types Observable and Flowable are used. The diference between Observable and Flowable is that Flowable handles back-pressure (that is, it implements a reactive streams protocol) while Observable does not. Flowable is better USE CASE NUMBER OF EXPECTED ITEMS RXJAVA TYPES IN THE STREAM NOTIFICATION, DATA FLOW 0..N Observable, Flowable ASYNCHRONOUS OPERATION PRODUCING 1..1 Single (MAYBE) A RESULT 0..1 Maybe ASYNCHRONOUS OPERATION THAT DOES 0 Completable NOT PRODUCE A RESULT Table 1. RxJava reactive publisher types 35 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 //reactive programming / suited for large streams of data coming from a source that supports back-pressure (for exam- ple, a TCP connection), while Observable is better suited at handling so-called “hot” observ- ables for which back-pressure cannot be applied (such as GUI events and other user actions). It is important to note that not all streams can support back-pressure. In fact, most of the streams conveying data captured in the physical world are not capable of this. Reactive pro- gramming libraries propose strategies such as bufers and acceptable data loss for handling these cases. Getting started with RxJava. It’s time to see some code and make reactive clearer. The com- plete project source code is available online. Clone or download this project and check the content of the rxjava-samples subproject. It uses RxJava 2.x and the logback-classic logging library. You will see later how it helps you understand threading with RxJava. In the previous section, we briely examined the diferent reactive types proposed by RxJava. The following class creates instances of these types and applies some basic operations: package samples; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Maybe; import io.reactivex.Single; import io.reactivex.functions.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RxHello { private static final Logger logger = LoggerFactory.getLogger(RxHello.class); public static void main(String[] args) { 36 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 //reactive programming / Single.just(1) .map(i -> i * 10) .map(Object::toString) .subscribe((Consumer<String>) logger::info); Maybe.just("Something") .subscribe(logger::info); Maybe.never() .subscribe(o -> logger.info("Something is here...")); Completable.complete() .subscribe(() -> logger.info("Completed")); Flowable.just("foo", "bar", "baz") .filter(s -> s.startsWith("b")) .map(String::toUpperCase) .subscribe(logger::info); } } Running this example yields output similar to this: 11:24:28.638 [main] INFO samples.RxHello - 10 11:24:28.661 [main] INFO samples.RxHello - Something 11:24:28.672 [main] INFO samples.RxHello - Completed 11:24:28.716 [main] INFO samples.RxHello - BAR 11:24:28.716 [main] INFO samples.RxHello - BAZ It is important to note that as with Java collection streams, no processing happens until an end event takes place. In RxJava, that event is a subscription. In this example, we used subscribe() 37 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 a stream of String values). "bar". }). We also introduced random failures. which just triggers the processing ■■ Two arguments to process events and errors ■■ Three arguments to process events. //reactive programming / with a single parameter. The following three methods can be used to notify subscribers: 38 ORACLE.nextInt(6) == 0) { subscriber. to process errors. "baz").create(subscriber -> { for (String s : data) { if (random. and to provide notiication when the processing is complete Creating publishers and recovering from errors. } subscriber.onError( new RuntimeException("Bad luck for you.onComplete(). The example above creates an Observable of String values (in other words. Of course.. } subscriber. Observable<String> source = Observable. which is a lambda called to receive each event. RxJava would be quite limited if cre- ating data streams such as Observables were limited to calling the just() factory method as we did in the previous example. All types of publishers support a create() method to deine the code to deal with new subscribers: List<String> data = Arrays.onNext(s).. where the values are being picked from a predeined list. Random random = new Random(). The following are other forms of Subscribe depending on the events the consumer wants to receive: ■■ No arguments.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .")).asList("foo". RxCreateObservable .RxCreateObservable - ======================================= 11:51:47.RxCreateObservable - ======================================= 11:51:47. i < 10. we can test this Observable 10 times: for (int i = 0.RxCreateObservable . source. error -> logger.info("Next: {}".469 [main] INFO samples. when a new value is sent to the subscriber.469 [main] INFO samples.RxCreateObservable .info("=======================================").469 [main] INFO samples.info("Done")).Next: foo 11:51:47.469 [main] INFO samples.RxCreateObservable . but presenting all options would be outside the scope of this article.469 [main] INFO samples. Next: bar 11:51:47.Next: bar 39 ORACLE. next). i++) { logger.469 [main] INFO samples.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .469 [main] INFO samples. () -> logger. Next: baz 11:51:47.RxCreateObservable . //reactive programming / ■■ onNext. Done 11:51:47. } We can observe successful completions as well as errors in the execution traces: 11:51:47. Because there is a good probability that errors will happen. possibly passing through intermediate operators before it reaches the subscriber ■■ onComplete to indicate that no more values will be sent ■■ onError to indicate that an error happened and that no further value will be sent. any Throwable can be used as an error value Note that create() is not the only way to deine custom publishers.469 [main] INFO samples.RxCreateObservable .subscribe( next -> logger. Next: foo 11:51:47.error("Whoops"). we haven’t cared much about multithreading.error("Whoops").469 [main] INFO samples.retry(5) .RxCreateObservable . but the following output shows an example of retries: 11:51:47.469 [main] ERROR samples. Done RxJava and threads. //reactive programming / 11:51:47.RxCreateObservable .RxCreateObservable .RxCreateObservable .472 [main] INFO samples. Next: foo 11:51:47. Next: bar 11:51:47. Because errors are random.472 [main] INFO samples. Next: foo 11:51:47. next).RxCreateObservable .472 [main] INFO samples.472 [main] INFO samples.RxCreateObservable .RxCreateObservable - ======================================= 11:51:47.Next: foo 11:51:47.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . your exact output trace will vary across executions.Whoops RxJava supports various ways to recover from errors.info("Done")).469 [main] ERROR samples. 5) 40 ORACLE. Next: bar 11:51:47.info("Next: {}". such as switching to another stream or providing a default value. Note that retries might use another thread for execution.RxCreateObservable . Let’s take another example and run it: Flowable. Another option is to use retry(): source .range(1.469 [main] INFO samples.RxCreateObservable . Above.RxCreateObservable . () -> logger.subscribe(next -> logger. So far.472 [main] INFO samples.Whoops 11:51:47. we should retry at most ive times with new subscrip- tions. error -> logger. we speciied that in case of error. Next: baz 11:51:47.472 [main] INFO samples. map(20) 12:01:01. and will notify its consumers. Schedulers are responsible for notifying the subscribers on the correct thread even if it’s not the thread used to call subscribe. with the most interesting being these: 41 ORACLE.map(i -> i * 10) .100 [main] INFO samples.100 [main] INFO samples.RxThreading . 40 12:01:01.map(i -> { logger.RxThreading . return i.100 [main] INFO samples.100 [main] INFO samples. 10 12:01:01. 20 12:01:01. 50 In fact.info("map({})".toString().100 [main] INFO samples.100 [main] INFO samples.RxThreading .100 [main] INFO samples. map(50) 12:01:01.RxThreading .schedulers.100 [main] INFO samples.RxThreading . both the operator processing and the subscriber notiications happen from that main thread.sleep(1000). i).RxThreading . }) .Schedulers class ofers several schedulers.RxThreading . map(40) 12:01:01. map(10) 12:01:01.RxThreading . Thread. RxJava ofers Schedulers to oload work to specialized threads and executors.RxThreading .RxThreading . on the same thread on which its subscribe method is called. By default. You can see from the logs that all processing happens on the main thread: 12:01:01.097 [main] INFO samples.subscribe(logger::info). The io.reactivex. 30 12:01:01. a publisher (and the chain of operators that you apply to it) will do its work.100 [main] INFO samples.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . map(30) 12:01:01. //reactive programming / . which is a shared thread for operations to execute in order ■■ from(executor) to oload all scheduled work to a custom executor Now.subscribeOn(Schedulers.128 [RxComputationThreadPool-1] INFO samples. we can specify how the subscription and observation will be scheduled: Flowable.map(i -> { logger. Thread.info("map({})".127 [RxComputationThreadPool-1] INFO samples. In this example.range(1.RxThreading .COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .subscribe(logger::info). return i.map(20) 42 ORACLE.map(10) 12:01:03. }) .toString().map(i -> i * 10) . Running the example gives an execution trace where you clearly see diferent threads being involved: 12:01:03.computation()) . logger. i). the map operations are invoked on the computation thread pool while the subscribe callback (logger::info) is invoked by a diferent thread (which does not change).sleep(1000).observeOn(Schedulers. The subscribeOn method speciies the scheduling for the subscription and operator processing. //reactive programming / ■■ computation() for CPU-intensive work with no blocking I/O operations ■■ io() for all blocking I/O operations ■■ single().info("===================================").single()) .RxThreading . 5) . while the observeOn method speciies the scheduling for observing the events. back to our previous example. 127 [main] INFO samples.128 [RxComputationThreadPool-1] INFO samples.reactivex.RxThreading .20 12:01:03. import io.RxThreading .128 [RxSingleScheduler-1] INFO samples. //reactive programming / 12:01:03.RxThreading =================================== Combining observables.Flowable.map(40) 12:01:03.Logger.128 [RxSingleScheduler-1] INFO samples.40 12:01:03.LoggerFactory. 43 ORACLE.128 [RxSingleScheduler-1] INFO samples.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .RxThreading .RxThreading . import io.RxThreading .Schedulers.128 [RxComputationThreadPool-1] INFO samples.50 12:01:04.map(30) 12:01:03.schedulers.128 [RxSingleScheduler-1] INFO samples.map(50) 12:01:03.slf4j.10 12:01:03.128 [RxSingleScheduler-1] INFO samples.RxThreading . RxJava ofers many ways to combine streams.reactivex.slf4j. as the following example shows: package samples. Merging streams provides a single stream that mixes elements from the various sources.128 [RxComputationThreadPool-1] INFO samples.RxThreading . import org. import org.30 12:01:03. We’ll illustrate that with the merge and zip operations.RxThreading . sleep(3000). Flowable.just( "abc".subscribe(obj -> logger. TimeUnit.MILLISECONDS. "def".generate(emitter -> emitter.subscribeOn(Schedulers.util. "jkl") . Flowable<Object> uuids = Flowable . intervals. 44 ORACLE.limit(10) .interval(100.computation()).getLogger(RxMerge. Schedulers. uuids) .map(tick -> "Tick #" + tick) .subscribeOn(Schedulers.limit(10) .concurrent.computation()).merge(strings. Flowable<String> strings = Flowable. public static void main(String[] args) throws InterruptedException { Flowable<String> intervals = Flowable .computation()) .randomUUID())) .onNext(UUID.TimeUnit.computation()). "ghi".subscribeOn(Schedulers.info("Received: {}". import java. //reactive programming / import java. obj)). Thread.util.UUID.class).COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . public class RxMerge { private static final Logger logger = LoggerFactory. RxMerge . obj)). which takes elements from various sources and assem- bles them: Flowable. s)) .zip(intervals.RxMerge . It produces a trace similar to this: 14:32:40.Received: Tick #0 {67e7cde0-3f29-49cb-b569-e01474676d98} -> abc 14:32:40.Received: Tick #2 {7b7d81b6-cc39-4ec0-a174-fbd61b1d5c71} -> ghi 14:32:40.424 [RxComputationThreadPool-7] INFO samples.324 [RxComputationThreadPool-7] INFO samples. //reactive programming / } } Running this example gives a trace in which elements from the various sources may be inter- leaved.RxMerge .format("%s {%s} -> %s". 45 ORACLE. uuids. such as services.info("Received: {}". and then producing a result based on what was received.subscribe(obj -> logger. zip() is useful for gathering data from other parties. Another useful option is zip().Received: Tick #1 {a0a0cc83-4bed-4793-9ee0-11baa7707610} -> def 14:32:40.Received: Tick #3 {ae88eb02-52a5-4af7-b9cf-54b29b9cdb85} -> jkl In real-world scenarios.127 [RxComputationThreadPool-7] INFO samples. u. s) -> String.RxMerge .224 [RxComputationThreadPool-7] INFO samples.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . u. i. (i. strings. Vert.Create a Vert. Eclipse Vert. Reactive programming addresses the asynchronous development model. However. embracing the asynchronous execution model is essential. Vert. The Vert. For each event. this approach comes with some drawbacks.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .vertx(). public class HttpApplication { public static void main(String[] args) { // 1 . An event loop is a thread consuming events from a queue. the system loses its responsiveness and the number of unprocessed events in the queue rises. //reactive programming / Implementing Reactive Systems with Reactive Programming While reactive programming lets you compose asynchronous and event-driven applications. For instance. your code can be single-threaded while handling lots of concurrent and entangled tasks.Vertx. // 2 . In this model. To successfully build responsive distributed systems in a world of cloud and containers. it looks for a handler interested in the event and calls it. The Vert.x instance Vertx vertx = Vertx.core. Fortunately. don’t lose sight of the overall goal.vertx. but you still need a task-based concurrency model and nonblocking I/O. Handlers are methods that receive an event as a parameter.x comes with a large ecosystem for implementing almost anything in an asynchronous and nonblocking way. import io. accessing databases.Create the HTTP server 46 ORACLE. Let’s look at a few examples.x provides building blocks for building modern web applications.x execution model is based on the concept of an event loop.x “hello world” application (code available online) is the following: package samples. and interacting with legacy systems.x provides these two missing pieces as well as RxJava-friendly APIs. The executed handlers must never block the event loop: if they do. getAbs("https://twitter.listen(8080).ext.createHttpServer() // 3 .Vertx. Now.WebClient.getName())) // 4 . } } For each incoming HTTP request (event).Create a Web client WebClient client = WebClient.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . retrieve a Twitter feed client .currentThread().Attach a request handler processing the requests .response() . Notice that the handler is always called by the same thread: the event loop thread.vertx. the request handler is called.end("Hello.core. you would do something like this: package samples.Start the server on the port 8080 .create(vertx).requestHandler(req -> req.vertx().send(res -> { 47 ORACLE.client. request handled from " + Thread. // 1 . vertx.requestHandler(req -> { // 2 . import io. //reactive programming / vertx.web.In the request handler. if you want to call another service (using HTTP) in the request handler.vertx.com/vertx_project") . import io.createHttpServer() . public class TwitterFeedApplication { public static void main(String[] args) { Vertx vertx = Vertx. HttpServer.vertx.reactivex.response().ext. This does not prevent handling concurrent requests. This is where RxJava comes into play. import io. public class RXTwitterFeedApplication { public static void main(String[] args) { 48 ORACLE.Write the response based on the result if (res.x event loop (in a single-thread manner).http.reactivex. import io.end(res.client. } }).COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . a single thread handles all the requests.web.Vertx.failed()) { req.vertx. However. //reactive programming / // 3 .listen(8080). import io.x nonblocking I/O.reactivex.client.result() . The previous code can be rewritten as follows: package samples.web.reactivex.core.WebClient. you can quickly see the issue: the code becomes diicult to understand because of the nested callbacks. } } This example relies on the Vert.core. so the entire code runs on the Vert.bodyAsString()).ext. It’s actually the opposite.cause(). } else { req.HttpResponse.getMessage()). import io.vertx.vertx.response().end("Cannot access " + "the twitter feed: " + res. }) . end(res)) // 6 .vertx().createHttpServer().requestStream().create(vertx). } } By restructuring the code around the RxJava reactive types.toFlowable() // 2 . server.listen(8080).For each request.Never forget to subscribe to a reactive type. WebClient client = WebClient.Write the response .map(HttpResponse::bodyAsString) // 4 .getAbs("https://twitter.onErrorReturn(t -> "Cannot access the twitter " + "feed: " + t.com/vertx_project") .rxSend() // 3 . call the twitter API .Extract the body as string . HttpServer server = vertx.response().getMessage()) // 5 . you beneit from the RxJava operators.subscribe().COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . // or nothing happens .Transform the sequence of request into a stream .flatMapCompletable(req -> client.Just transform the restul into a completable .In case of a failure . 49 ORACLE.toCompletable() ) // 7 . server // 1 . //reactive programming / Vertx vertx = Vertx.doOnSuccess(res -> req. By default. and their response times might greatly vary. They let you organize your code into a set of loosely coupled components. The verticle is designed with the HTTP port being conigurable. 50 ORACLE. and they use an actor-like deployment and concurrency model. generally a Java class.getLogger(BiddingServiceVerticle. @Override public void start(Future<Void> verticleStartFuture) throws Exception { Random random = new Random(). Bidding service verticle. and so on). Let these services ofer simple HTTP/JSON endpoints. and you want to ofer an edge service to select the best ofer at a point in time.x to deploy a set of verticles. messages. When the application starts.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . We will simulate such a system by developing the following: ■■ A bidding service. as follows: public class BiddingServiceVerticle extends AbstractVerticle { private final Logger logger = LoggerFactory. //reactive programming / Implementing a Reactive Edge Service Let’s look at another simple yet efective example. and provide time-bound guarantees for returning the best ofer. it instructs Vert.class). Instead of starting the application using a main method. but this does not result in any loss of generality. A verticle is a chunk of code. we can show how to combine request streams. Verticles are simple and scalable. we are going to use verticles. All verticles will be deployed within the same application as we are prototyping. with artiicial delays and random errors ■■ An edge service to query services through HTTP By using RxJava. these services might fail temporarily.x. deal with failures. The complete code is available in the vertx-samples subproject. Obviously in real-world scenarios. verticles are executed by the event loop and observe diferent types of events (HTTP requests. that is deployed and run by Vert. TCP frames. Suppose that you have three services ofering bids. put("clientRequestId".nextInt(20) == 1) { context. router..nextInt(20). myBid). //reactive programming / String myId = UUID. clientId). and accessor methods such as getInteger support a default value as a second argument. the default HTTP port is 3000.put("bid".x web router to accept HTTP GET requests on path /offer: Router router = Router.setTimer(artificialDelay. // (. int myBid = 10 + random. JsonObject payload = new JsonObject() .get("/offer"). id -> { if (random..getInteger("port". if (clientIdHeader != null) { payload.toString(). 3000).handler(context -> { String clientIdHeader = context.getHeader("Client-Request-Id").response() . and it makes use of a ran- dom number generator.randomUUID(). int portNumber = config(). String clientId = (clientIdHeader != null) ? clientIdHeader : "N/A".COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . } long artificialDelay = random.setStatusCode(500) 51 ORACLE. The service has a random UUID to identify its endpoint in responses.nextInt(1000).) } } The config() method provides access to a verticle coniguration.put("origin". myId) .request() .router(vertx). The next step is to use the Vert. vertx. So here. Finally.info("Bidding service listening on HTTP " + "port {}". myBid. 52 ORACLE. logger.createHttpServer() .error("{} injects an error (client-id={}. "application/json") . the HTTP server is started as usual: vertx. portNumber). Note that to simulate failures. myBid. we built in a 5 percent chance of failure (in which case.encode()). ar -> { if (ar. } else { context. clientId. verticleStartFuture.info("{} offers {} (client-id={}.error("Bidding service failed to start".listen(portNumber.000 milliseconds. " + "artificialDelay={})".cause()). artificialDelay).end(payload. myId.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . ar. //reactive programming / . } }).end(). }). " + "artificialDelay={})".requestHandler(router::accept) .complete(). the ser- vice issues an HTTP 500 response) and the inal HTTP response is delayed by using a random timer between 0 and 1.succeeded()) { logger. artificialDelay). } else { logger. myId.putHeader("Content-Type".response() . clientId. logger. @Override public void start(Future<Void> startFuture) throws Exception { webClient = WebClient.put("host".put("port".put("host".put("port".put("host". "/offer")) . private WebClient webClient. private List<JsonObject> targets. "localhost") .fail(ar.add(new JsonObject() . 3001) .x. "/offer")).add(new JsonObject() . //reactive programming / verticleStartFuture.getLogger(BestOfferServiceVerticle.cause()). 53 ORACLE.put("port". 3000) .put("path". private final Logger logger = LoggerFactory . 3002) .class). "localhost") .put("path". Here are the preamble and the start method of the verticle class: public class BestOfferServiceVerticle extends AbstractVerticle { private static final JsonArray DEFAULT_TARGETS = new JsonArray() .put("path". } }).create(vertx). "/offer")) .add(new JsonObject() .COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . Edge service: selecting the best ofer. This service is implemented using the RxJava API pro- vided by Vert. "localhost") . x. port. } else { logger.collect(Collectors.reactivex.AbstractVerticle class.getJsonArray("targets".x APIs that return RxJava objects are preixed with “rx”: here rxListen returns a Single<HttpServer>.complete().rxListen(8080) . with the defaults being on the local host and ports 3000.fail(error). } }). startFuture. 3001. error) -> { if (error != null) { logger. DEFAULT_TARGETS) .class::cast) . 54 ORACLE. Such coniguration can be passed as a JSON array containing JSON objects with host.info("The best offer service is running " + "on port 8080"). vertx. The server is not actually started until we subscribe. and path keys. //reactive programming / targets = config().toList()). startFuture.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . ■■ It is possible to specify the target services. error).core. ■■ Variants of the Vert.map(JsonObject. and 3002. } There are several interesting points in this code: ■■ To access the RxJava API ofered by Vert.subscribe((server. we import and extend the io.createHttpServer() .vertx.requestHandler(this::findBestOffer) .error("Could not start the best offer " + "service".stream() . getAndIncrement()). true) .stream() .valueOf(requestIds.encodePrettily()). body.scheduler(vertx)) .getString("host"). best response and eventually ends the HTTP response: private final AtomicLong requestIds = new AtomicLong().MAX_VALUE).map(HttpResponse::body) . t. t.get(t. It irst issues HTTP requests to each service.getInteger("port").as(BodyCodec. requestId.onErrorReturnItem(EMPTY_RESPONSE)) 55 ORACLE. RxHelper. and then it reduces them to the single. return body. String.put("empty".jsonObject()) .map(body -> { logger.rxSend() . }) . List<Single<JsonObject>> responses = targets.getString("path")) . private static final JsonObject EMPTY_RESPONSE = new JsonObject() .MILLISECONDS.info("#{} received offer {}".retry(1) .put("bid". //reactive programming / We can now focus on the implementation of the findBestOffer method.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . TimeUnit. private void findBestOffer(HttpServerRequest request) { String requestId = String.timeout(500.map(t -> webClient . obtaining a list of Single<JsonObject> responses. Integer.putHeader("Client-Request-Id".valueOf(requestId)) . } return acc. }.collect(Collectors.setStatusCode(502) . requestId. Single.subscribe(best -> { logger.merge(responses) .encode()). request.containsKey("bid") && isHigher(acc.response() . //reactive programming / .info("#{} best offer: {}".flatMapSingle(best -> { if (!best.error("#{} ends in error".containsKey("empty")) { return Single. best.toList()). } }) .COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .reduce((acc.end().response() . request. error -> { logger. "application/json") .encodePrettily()). }).end(best.putHeader("Content-Type". next) -> { if (next. error).just(best). } 56 ORACLE.error(new Exception("No offer " + "could be found for requestId=" + requestId)). requestId. }) . } else { return Single. next)) { return next. Otherwise.setInstances(2)). Deploying verticles and interacting with the services.deployVerticle(new BiddingServiceVerticle()). If no service can deliver a bid within 500 milliseconds. which is how we avoid waiting for all responses and errors to arrive.deployVerticle(new BiddingServiceVerticle(). vertx. resulting in an HTTP 502 error. flatMap. new DeploymentOptions().setConfig( new JsonObject(). } } 57 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . The whole processing is just a matter of composing functional idioms such as map. Note that all RxJava operations that expect a scheduler can use RxHelper::scheduler to ensure that all events remain processed on Vert. and reduce and handling errors with a default value. new DeploymentOptions(). new DeploymentOptions().put("port".BestOfferServiceVerticle". 3002))). no ofer is being made. 3001))). ■■ The processing times out after 500 milliseconds before returning an empty response. the best ofer is selected among the responses received. ■■ A retry is attempted if the service issued an error. vertx.setConfig( new JsonObject().deployVerticle("samples. The main verticle code is as follows: public class MainVerticle extends AbstractVerticle { @Override public void start() { vertx. vertx.x event loops.deployVerticle(new BiddingServiceVerticle().put("port". //reactive programming / It is interesting to note the following for each HTTP request: ■■ The response is converted to a JsonObject using the as() method. 9.x-eventloop-thread-1] ERROR samples. pass- ing the HTTP port those services should listen on in the JSON coniguration. but note that there will be no conlict because Vert. //reactive programming / We deploy the bidding service three times on diferent ports to simulate three services.1 200 OK Content-Length: 83 Content-Type: application/json { "bid": 21.9 HTTP/1. Let’s talk to the service on port 3000: $ http GET localhost:3000/offer 'Client-Request-Id:1234' --verbose GET /offer HTTP/1. We also deploy the edge service verticle with two instances to process the incoming traic on two CPU cores rather than one. We can now interact with the HTTP services. for instance.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . "clientRequestId": "1234".1 Accept: */* Accept-Encoding: gzip. deflate Client-Request-Id: 1234 Connection: keep-alive Host: localhost:3000 User-Agent: HTTPie/0. by using the HTTPie command- line tool.x distributes the traic in a round-robin fashion.BiddingServiceVerticle - 58 ORACLE. "origin": "fe299565-34be-4a7b-ac09-d88fcc1e42e2" } The logs reveal both artiicial delays and errors: [INFO] 16:08:03. The two instances will listen on the same HTTP port.443 [vert. BiddingServiceVerticle - d803c4dd-1e9e-4f76-9029-770366e82615 offers 16 ( client-id=0.BiddingServiceVerticle - 6358300b-3f2d-40be-93db-789f0f1cde17 offers 17 ( client-id=0.x-eventloop-thread-1] INFO samples. artificialDelay=656) [INFO] 16:12:51. artificialDelay=934) Similarly.BiddingServiceVerticle - 6358300b-3f2d-40be-93db-789f0f1cde17 offers 10 ( client-id=1234. artificialDelay=724) [INFO] 16:12:52.869 [vert.BiddingServiceVerticle - 966e8334-4543-463e-8348-c6ead441c7da offers 14 ( client-id=0.006 [vert.644 [vert.935 [vert.x-eventloop-thread-2] INFO samples. //reactive programming / 6358300b-3f2d-40be-93db-789f0f1cde17 injects an error ( client-id=1234. you can play with the edge service. observe responses.x-eventloop-thread-3] INFO samples.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . and check the logs to see how a response is being assembled. artificialDelay=792) 59 ORACLE.x-eventloop-thread-1] INFO samples. artificialDelay=N/A) [INFO] 16:11:10. Sometimes you will get an error: $ http GET localhost:8080 'Client-Request-Id:1234' HTTP/1.1 502 Bad Gateway Content-Length: 0 This is because all responses took longer than 500 milliseconds to arrive and some services injected an error: [INFO] 16:12:51. x core developer. The key point in this sample is that the combination of Vert. mobile app development.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . 60 ORACLE. scalable.x. HTTP/REST microservices. Wisdom Framework. sophisticated modern web applications. Reactive programming lets you compose asynchronous and event-driven applications by manipulating and combining data streams. Modern reactive programming libraries such as RxJava implement reactive streams to handle back-pressure. He is a longtime open source developer. or a full-blown back-end message-bus application. you have seen how Eclipse Vert. This article just scratched the surface. and Eclipse Vert.x. By using the execution model and nonblocking I/O capabilities promoted by Vert. Whether it’s simple network utilities. you are on the path to becoming truly reactive.x and RxJava ofers a declara- tive and functional model for describing how to perform and process a lexible number of net- work requests while remaining purely driven by asynchronous events. However. </article> Clement Escoier (@clementplop) is a principal software engineer at Red Hat. Don’t lose sight that you want to build better systems that are responsive. Julien Ponge (@jponge) is an associate professor at INSA Lyon and a researcher at the CITI-INRIA laboratory. //reactive programming / Sometimes you will observe that only one or two responses have been taken into account.x combines reactive programming and the asyn- chronous execution model to build reactive systems. where he is working as a Vert.x gives you signiicant power and agility to create compelling. Conclusion In this article. Vert. continuous delivery. robust. having created IzPack and the Golo programming language.x team. twenty-irst-century applications the way you want to. He has been involved in projects and products touching many domains and technologies such as OSGi. including Apache Felix. Escoier is an active contributor to many open source projects. and interactive. Ponge is currently on leave from INSA and working as a delegated con- sultant to Red Hat on the Vert. high-volume event processing. iPOJO. and is now a member of the Eclipse Vert. Vert.x is a great it. and DevOps. a reactive approach is not limited to reactive programming.x project. which provides reactive capabilities for the Spring Framework.] The Spring team has a project called Reactor.” on page 32. a client must be able to push back. and RxJava.x. Publisher is a producer of values that might eventually arrive. JOSH LONG R eactive programming is an approach to writing software that embraces asynchronous I/O. This is a fundamental aspect of low control in distributed systems. The Fundamental Data Types The Reactive Streams initiative deines four data types. such as Akka Streams. Many projects. rejecting work it can’t handle. —Ed.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . Asynchronous I/O inverts the normal design of I/O processing: clients are notiied of new data instead of asking for it. A Publisher produces values of type T. Vert. so. //reactive programming / Reactive Spring Proceeding from fundamentals. which has been summarized in the Reactive Streams initiative—an informal standard of sorts. support reactive programming. always the risk that too many notiications will overwhelm a client. The idea is simple: alleviate ineicient resource utilization by using resources that would otherwise sit idle as they waited for I/O activity. “Going Reactive with Eclipse Vert. use the Spring Framework to quickly build a reactive application. the ability of the client to signal how much work it can manage is called back-pressure. There is. 61 ORACLE. as shown in Listing 1. Asynchronous I/O is a small idea that portends big changes for software.x and RxJava. [Vert. There’s common ground across these diferent approaches. of course. In reactive programming.x and RxJava are examined in detail in the accompanying article. This approach frees the client to do other things while waiting for new notiications. Listing 2: The Reactive Streams Subscriber package org. as shown in Listing 3.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . it results in a Subscription. //reactive programming / Listing 1: The Reactive Streams Publisher<T> package org. } When a Subscriber subscribes to a Publisher. public interface Subscription { public void request(long n). Listing 3: The Reactive Streams Subscription package org.reactivestreams. public void onComplete(). public interface Subscriber<T> { public void onSubscribe(Subscription s). } A Subscriber subscribes to a Publisher. as shown in Listing 2. } 62 ORACLE. public void onError(Throwable t).reactivestreams. public interface Publisher<T> { void subscribe(Subscriber<? Super T> s). receiving notiications on any new values of type T.reactivestreams. public void onNext(T t). public void cancel(). or WebSocket endpoints. Listing 4: The Reactive Streams Processor package org. it builds on top of the Reactive Streams speciication.util.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . It ships with adapters that allow it to 63 ORACLE. it deines types for interoperability. Spring Framework 5. Flux. Server-Sent Events (SSE). but they go much further than the Reactive Streams speciication. is a Publisher that produces zero or more values.0 provides these things.reactivestreams. Publisher<R> { } The speciication is not meant to be a prescription for the implementations. Reactor The Reactive Streams types are not enough. The second. It provides two specializations of Publisher<T>. Mono<T>. They need to produce and consume HTTP. instead. It includes a new reactive runtime and component model called Spring WebFlux. Reactor types compose nicely: the output of one thing can be the input to another. Applications need to talk to data sources. They support authentication and authorization. //reactive programming / A Publisher that is also a Subscriber is called a Processor. R> extends Subscriber<T>.concurrent. The Reactive Streams types eventually found their way into Java 9 as one-to-one semantically equivalent interfaces in the java. It’s unbounded. Pivotal’s Reactor project is a good choice here. Spring WebFlux does not depend on or require the Servlet APIs to work. it’s only a foundation. They both provide ways to process a stream of values. They’re both publishers and you can treat them that way. public interface Processor<T. Reactive Spring As useful as project Reactor is. It was released in September 2017 and builds on Reactor and the Reactive Streams speciication. which is shown in Listing 4.Flow class. you’ll need higher-order implementations to sup- port operators such as iltering and transformation. is a Publisher that produces one or zero values. The irst. Example Application Let’s build a simple Spring Boot 2. 64 ORACLE. "security. but that is not required.springframework. Kotlin (optionally). You could call the project Library or something like that. It also provides a Netty- based web server.example.setProperty("spring. import org. args).COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . which works with a baseline of Java 8 and Java EE 7.frpjava"). Click Generate and it’ll download an archive. Make sure that some version of Spring Boot 2. even if most of the project I am building is in Java. Let’s look at an example. Actuator. The stock standard Spring Boot application has an entry class that looks like Listing 5.run(LibraryServiceApplication.springframework.active".profiles. I often use the Kotlin language. //reactive programming / work on top of a servlet engine. @SpringBootApplication public class LibraryServiceApplication { public static void main(String[] args) { System. I keep Java artifacts collocated in a Kotlin project. import org.libraryservice.0 (or later) is selected in the version drop-down menu. and Lombok. Go to the Spring Initializr.boot. I chose Maven for the purposes of this article. if need be.0 application that represents a service to manage books. Listing 5: The empty husk of a new Spring Boot project package com. Reactive Security. You’re writing a service to manage access to books in the library. Spring Framework 5. is the foundation for changes in much of the Spring ecosystem. Select the elements you’ll need: Reactive Web. Reactive MongoDB.SpringBootApplication. so give this project the artifact ID library-service. Unzip it and open it in your favorite IDE that supports Java 8 (or later). and Maven. SpringApplication.boot.class. While you could have chosen Gradle in the Spring Initializr.SpringApplication.authorization.autoconfigure. let’s use them to manage some data.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . Cassandra. private String title.AllArgsConstructor. Listing 6: A MongoDB @Document entity.mapping. and Couchbase). Redis.Id. as shown in Listing 6.springframework. import lombok.Data. } 65 ORACLE. private String author. The release also introduces new reactive repository and template implementations. Create a new entity called Book. //reactive programming / } } Data Access with Reactive Spring Data Modules The most recent release of Spring Data debuts support for reactive data access when that is sup- ported in the underlying datastores (such as MongoDB. Because you have the reactive MongoDB driver and Spring Data module on the classpath. import org. import org.data.annotation.core. Book package com.Document.data. import lombok.example.NoArgsConstructor. import lombok. @Document @Data @AllArgsConstructor @NoArgsConstructor public class Book { @Id private String id.libraryservice.mongodb.springframework. import org.data.Flux.ReactiveMongoRepository.slf4j.example. Let’s create an ApplicationRunner that deletes all the data in the data source. } Install Some Sample Data With that. Finally. Spring Boot invokes the #run(ApplicationArguments) method when the application has started. then maps them to Book entities. This should look very familiar to anyone who has ever used Spring Data. import org. you now have enough to install some sample data (just for your demo). See Listing 7. and input can be given as Publisher instances. //reactive programming / Next.core.ApplicationRunner. and then persists those books. it queries all the records in the data source and then prints out everything. Listing 8: An ApplicationRunner to write data package com. public interface BookRepository extends ReactiveMongoRepository { Flux findByAuthor(String author).ApplicationArguments. 66 ORACLE.boot.repository. then emits a few book titles.springframework. create a Spring Data repository to support the data management lifecycle of the entity.springframework.mongodb.extern. import reactor. import org.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .Slf4j.libraryservice.boot.springframework. Listing 8 shows all this.publisher. import lombok. passing wrappers for the arguments (String [] args) into the application.libraryservice. except that the reposi- tory supports reactive interactions: methods return Publisher types.example. Listing 7: A reactive Spring Data MongoDB repository package com. thenMany(this.springframework. import reactor.thenMany( Flux.just( "Cloud Native Java|jlong".bookRepository . "Spring Security 3. @Slf4j @Component class SampleBookInitializer implements ApplicationRunner { private final BookRepository bookRepository.Component.Flux. //reactive programming / import org. and then it writes them to the database.info(book. tuple[1])) .stereotype.bookRepository::save) .1|rwinch". First the strings are split by the | delimiter. tuple[0].findAll()) . SampleBookInitializer(BookRepository bookRepository) { this.flatMap(this.core. 67 ORACLE.map(tuple -> new Book(null.toString())). "Spring in Action|cwalls")) . } @Override public void run(ApplicationArguments args) throws Exception { this.bookRepository = bookRepository.map(t -> t.split("\\|")) .deleteAll() .publisher.bookRepository. } } The example looks at the titles of various books and one of the (possibly numerous) books’ authors.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .subscribe(book -> log. I turn my focus to the results of inding all records and then to logging them for inspection. //reactive programming / Then the title and book author are used to create a Book.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . you’d see that the thread on which processing is run- ning is diferent than the main thread (which is named main). among other things. if you want to look at the complete application. I’ll use Spring Framework 5. but Reactor provides hooks to process each emitted value. it won’t be executed until it is activated.setFactory(Factory). This code deines a pipeline. The pipeline is not eager. as well as any exceptions thrown.0 to stand up a REST API and to implement secure access to this data.getName(). Were you to put a breakpoint in any of the lambdas in Listing 8 and then inspect Thread. You can specify on which thread a particu- lar Publisher should run when it subscribes by specifying Mono::subscribeOn(Scheduler) or Flux::subscribeOn(Scheduler). Then. and he speaks frequently at developer conferences. the source code is all online. 68 ORACLE. Conclusion You have now used Spring Boot and Spring Initializr to quickly create and run a reactive data application that hews closely to the requirements of reactive development. You can specify the default global Scheduler you’d like to use by calling Schedulers. Reactor defers to a Scheduler implementation for its processing. You activate the pipeline by subscribing to it (the last step in the code in Listing 8). In the second (and inal) part of this article. He is the author of several books on Spring programming. each operator deines a stage in a pipeline. Meanwhile. MongoDB. that is. The result of the save operation is a Mono<Book>. Publisher deines only one type of subscription. </article> Josh Long (@starbuxman) is a Java Champion and a Spring developer advocate at Pivotal.currentThread(). Something needs to sub- scribe to each of those resulting Publisher<T> instances. so I use the flatMap operator. Then the records are saved to the data source. and Command Query Responsibility Segregation (CQRS) ofer another way to model applications that enables interesting solutions and use cases. //beyond CRUD / Command Query Responsibility Segregation with Java Combining event sourcing and event-driven architectures to build scalable. Once an update is performed. That aspect comes in handy when users read the current state. especially with the rising demands of scalability. all transactions and interactions need to modify the system in a consistent way. For example.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . This sounds nor- mal to enterprise developers but can become quite complex when you are dealing with compet- ing transactions—for example. It’s harder to comprehend the current state and ind potential bugs if the whole history is not available. including all domain objects. eventually consistent systems SEBASTIAN DASCHNER M ost of today’s enterprise applications are based on a CRUD data model that is simple and straightforward to implement. when users want to update their contact information and at the 69 ORACLE. Before getting into CQRS. The domain entities are stored in the database or in an in-memory representation with their properties as they are at any given moment. This can make it tricky to reproduce and debug situations in production. Another challenge of CRUD-based models is that due to storing only the current state. the objects are then in a new state and their old state is forgotten. Shortcomings of CRUD-Based Applications A CRUD-based application always contains the current state of the system. I’ll quickly describe some of the limitations of the CRUD model. event-driven architectures. but it falls short in other aspects. is in its current state and how it got there. Event sourcing. a model that is solely CRUD-based has no information about the history or the context—why the system. Verifying and maintaining these consistent states can become both redundant and complex. a deletion action also changes the current state by just adding a CustomerDeleted event to the log—no entry is actually deleted. You can calculate your cur- rent balance by starting at zero and adding or subtracting the amounts of all transactions accordingly. and durability [ACID] transactions) until the update has taken place. Because CRUD-based applications need to store the status quo and keep a consistent state within their data model. The example in Figure 1 shows a simple set of customer-related events that can be used to arrive at a customer representation. If several distributed systems are involved. The application does not necessarily contain the current state.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . These events are the single source of truth in the system. Usually. for example. asynchronous way—it makes sense to model tic locking results in one transaction winning applications in an event-driven way. 70 ORACLE. //beyond CRUD / same time some other use case updates their account balance. This implies that. To maintain consistency. event-sourced systems store all modiications that happen to a system as atomic entities. such applica- tions need to lock the data (as in good old atomicity. there should be no need to mutually exclude either transaction. they cannot scale horizontally. A similar problem occurs when a use case updates business objects whose new states require veriication to keep the system in a consistent state. but it can be calculated by applying all events that have happened in the past. The most prominent example for this model is bank accounts. isolation. The events are atomic and immutable. strictly speaking. If this information afects the Because the real world is all about same database entries. the synchronization will become a bottleneck. because they happened in the past and cannot be undone. consistency. the two activities lead distributed collaboration—often in an to a locking situation. over the other. Event Sourcing In contrast to a CRUD data model. this optimis. However. Another advantage of event-sourced systems is the possibility of calculating statistics and implementing future use cases later. Because all atomic information that ever was applied to the system is available. enterprise systems use so-called snapshots that represent the state as of a certain moment in time. answering the question. One of the beneits of this architecture is that the full history of what has happened enables developers to reproduce complex use-case scenarios and debug the system with ease.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . CustomerCreated CustomerAddressChanged CustomerAccountVerified John_Doe_123 : Customer Figure 1. This is. an optimization technique to deal with a growing number of events—the atomic events remain the golden source of truth. which again can be persisted. Events that determine the current state of a customer entry 71 ORACLE. Events that arose after that moment are then applied to the snapshot in order to form a new state. //beyond CRUD / While the current state could be calculated on demand using all events that have happened in the past. however. That makes it possible to imple- ment future use cases on events that happened in the past—as if that new functionality was always there. you can use this information and simply redeploy the application with updated behavior and recalculate the status from the events. “How many users signed up on a Tuesday?” is possible using the information contained in the events even if this functionality wasn’t considered previously. For example. you need to model applica- tions with event sourcing. For ordering a cup of cofee at a café. If you want to model distributed systems—such as microservices—that aim to maintain a consistent state throughout several systems. Coffee order system Bean storage system placeOrder() OrderPlaced validateOrder() completeOrder() OrderAccepted OrderCompleted Order_123 : Order Figure 2. Example event-driven architecture 72 ORACLE. However.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . you would irst attempt to place an order. you split up a transaction into several transactions that still maintain consistency—at least in an eventually consistent way. //beyond CRUD / Event sourcing alone doesn’t imply that the application has to be implemented using an event-driven or CQRS approach. which results in an OrderPlaced event—or an error. Because distributed transactions don’t scale well. An event-driven architecture (see Figure 2) realizes use cases that involve multiple systems by collaborating via commands and events. for example. Event-Driven Applications In contrast to the beneits of an event-sourced system. the motivations behind event-driven applications difer. in order to apply CQRS. you need to take transactions into account. //beyond CRUD / This OrderPlaced event then causes the cofee bean storage to check whether there are beans available and to publish either an OrderAccepted event or an OrderFailedInsufficientBeans event. they either return successfully or throw an error. This principle is simple in theory but has important implications. the waiter accepts your order—even though it’s possible that for some reason the cofee will never make it to you. I will introduce the CQRS principle. The current state of the order is calculated by applying all events related to that order as in an event-sourced system. another drink. CQRS causes methods to either modify the state of the system without returning any value or to return values without any side efect. The commands (that is. the writes) are not supposed to return values. The queries (that is. One of the benefits of separating the the waiter will come back later and apologize responsibilities of reads and writes in for not being able to deliver the cofee and the CQRS model is the fact that the query and will ofer a compensating transaction—even command sides can scale independently. which prescribes separating the responsibilities of reads and writes. This way of modeling causes the process to be eventually consistent. In that case. though the order was accepted in the irst place. If you compare this way of modeling to the real world. Eventually. the applications collaborate only by events that are published to 73 ORACLE. Once you split up a sys- tem following this approach. and because the appli- cation ensures that all events are published in a reliable way. you can see that these methods of collaboration are common.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . or your money back. When you order a cup of cofee. Enter CQRS Now that I’ve summarized implementing event-driven and event-sourced applications. the reads) only return data (see Figure 3). you will end up with your cofee. the inal outcome of the use cases will be consistent. Because the real world is all about distributed collaboration—often in an asynchronous way—it makes sense to model applications in an event-driven way. placeOrder(Order).COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . the service per- forms the action using the domain object representations in its internal storage and publishes events (OrderPlaced). Example of a CQRS implementation 74 ORACLE. When an update command. The command and query components maintain their own domain object rep- resentations by consuming the events from the hub and updating the state of their internal model. The events that are published from the event store are consumed by all subscribed consum- void placeOrder() CoffeeOrder getOrder() DB CommandService QueryService DB OrderPlaced OrderPlaced EventStore Figure 3. reaches the command side. The services are coupled only by the event store and can operate and be deployed independently from each other. //beyond CRUD / an event store. The storage representations of each side can difer and be optimized according to their best it. this service returns the current state from its internal storage. When the client reads at the query side. the read operations outnumber the write operations. Because more and more events are stored in the system over time. for example. bean storage (beans). returning replicated data has a positive impact on the overall performance. //beyond CRUD / ers to update their internal model—but only one subscriber. a greater number of query service instances to scale out just the read side. is supposed to trigger further commands from these events. and cofee brewing (barista). Another beneit of this separation is the given failover capacity—at least for the read side. Example CQRS Application As an example. Publishing the events has to happen in a reliable way to keep the system in a consistent state in the long run. Because being eventually consis- tent on the read side is. Benefits of CQRS One of the beneits of separating the responsibilities of reads and writes in the CQRS model is the fact that the query and command sides can scale independently. Each service is free to choose its internal domain object representation. the clients can still access the last state. I’m using a scalable cofee shop that consists of three services. and the collaboration is done using 75 ORACLE. Updating the representation continuously and using these models in the commands and queries maintains a constant level of performance. because they implement event sourcing as well. this cached state is still available if the event store goes down. the overall performance of operations would decrease if the application state were solely calculated on demand by applying all events each time. I will show an actual CQRS implementation in a Java EE application. in most cases. This corresponds to the concept of snapshots.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . EventHandler. The domain model representations of each of the services solve the problem of the rising numbers of events in an event-sourced system. In typical enterprise appli- cations. Applications that implement CQRS also have the capability to implement further use cases that operate on events from the past. Using CQRS enables you to deploy. Even though no new events can be written. not a big problem. Now. Because all instances maintain an eventually consistent representation of the system’s state. responsible for order management (orders). When a client creates an order.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . the command service publishes an event (OrderPlaced) and returns the request successfully—even though the system can’t tell yet whether the order will be inished successfully. Use cases for ordering a cup of cofee 76 ORACLE. the services handle the events accordingly and update their representation. The business use cases for ordering a cup of cofee are shown in Figure 4. //beyond CRUD / Apache Kafka as the event hub. The client can request the status of the order from the query service Coffee order system Bean storage system Barista system orderCoffee() OrderPlaced validateBeans() OrderBeansValidated acceptOrder() OrderAccepted fetchBeans() BeansFetched makeCoffee() startOrder() CoffeeBrewStarted() OrderStarted finishOrder() CoffeeBrewFinished OrderFinished deliverOrder() CoffeeDelivered OrderDelivered Figure 4. Once events are published to Kafka. getOrderInfo().publish(new OrderPlaced(orderInfo)). with the state being updated on incoming events. This service is the use-case entry point from both the application boundary and the event handler. 77 ORACLE. public void placeOrder(OrderInfo orderInfo) { eventProducer. The appli- cation boundary contains the external REST interface.get(orderId) . The following code shows examples for the order command service. a *CommandService and *QueryService. } void acceptOrder(UUID orderId) { OrderInfo orderInfo = coffeeOrders. @Inject CoffeeOrders coffeeOrders. Application Architecture The Java EE application is organized with the Entity Control Boundary (ECB) pattern. public class OrderCommandService { @Inject EventProducer eventProducer. and the event handling functionality that will call subsequent commands. The entity packages consist of the event and domain object deinitions. as well as functionality to access Kafka. The command service contains the business methods and publishes events at the event hub. The query service accesses the storage only to return data.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . The control packages contain the storage representations that contain the current domain object representations. //beyond CRUD / anytime. which processes the commands by publishing the events to the event hub. } } The order query service. } void finishOrder(UUID orderId) { eventProducer. reason)). public CoffeeOrder getOrder(UUID orderId) { 78 ORACLE. } void cancelOrder(UUID orderId. which keeps track of the orders.publish(new OrderStarted(orderId)).publish( new OrderCancelled(orderId. is used to retrieve the cofee order repre- sentations.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . //beyond CRUD / eventProducer. String reason) { eventProducer. It uses the cofee order store. } void deliverOrder(UUID orderId) { eventProducer. public class OrderQueryService { @Inject CoffeeOrders coffeeOrders.publish(new OrderDelivered(orderId)). shown in the following code.publish(new OrderAccepted(orderInfo)).publish(new OrderFinished(orderId)). } void startOrder(UUID orderId) { eventProducer. I’m using solely in-memory storage with the Kafka events being redelivered and reapplied at application startup.place(event.getOrderInfo() . } 79 ORACLE.getOrderId(). The store itself observes these CDI events and updates and stores the domain object representations. CoffeeOrder> coffeeOrders = new ConcurrentHashMap<>().getOrderInfo())).getOrderId().putIfAbsent(event.get(orderId). public CoffeeOrder get(UUID orderId) { return coffeeOrders. o -> o. } } Incoming events are delivered as Contexts and Dependency Injection (CDI) events within the application. applyFor(event.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . In a production envi- ronment. //beyond CRUD / return coffeeOrders. } public void apply(@Observes OrderPlaced event) { coffeeOrders. this functionality would likely be integrated with a persistent database that stores the last calculated state.get(orderId).BEAN) public class CoffeeOrders { private final Map<UUID. @Singleton @Startup @ConcurrencyManagement(ConcurrencyManagementType. For simplicity.getOrderInfo(). in the following code. new CoffeeOrder()). } public void apply(@Observes OrderStarted event) { applyFor(event.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . } public void apply(@Observes OrderFinished event) { applyFor(event. CoffeeOrder::start).get(orderId).getOrderId(). } public void apply(@Observes OrderAccepted event) { applyFor(event. } public void apply(@Observes OrderDelivered event) { applyFor(event.getOrderId(). CoffeeOrder::finish). } private void applyFor(UUID orderId. CoffeeOrder::deliver). } } 80 ORACLE.accept(coffeeOrder). Consumer<CoffeeOrder> consumer) { CoffeeOrder coffeeOrder = coffeeOrders.getOrderId(). CoffeeOrder::accept).getOrderInfo(). if (coffeeOrder != null) consumer.getOrderId(). CoffeeOrder::cancel). //beyond CRUD / public void apply(@Observes OrderCancelled event) { applyFor(event.getOrderId(). This handler calls the command service for further processing of orders.getOrderId()). @Inject OrderCommandService orderService. //beyond CRUD / For simplicity. @Inject Event<CoffeeEvent> events.acceptOrder(event. both the query and command services are using the same CoffeeOrders instance. 81 ORACLE. It both con- sumes Kafka messages and ires the corresponding CDI events. this could be split into several components or systems and further optimized for each side accordingly. public void handle(@Observes OrderBeansValidated event) { orderService. @Resource ManagedExecutorService mes. However. The connection for incoming events that trigger subsequent commands is done in the event handler. @Singleton @Startup public class OrderEventHandler { private EventConsumer eventConsumer. @Inject Logger logger.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . @Inject Properties kafkaProperties. For my purpose—to show an example implementation—this model is suicient. } public void handle(@Observes CoffeeDelivered event) { orderService. } @PostConstruct private void initConsumer() { kafkaProperties. "beans").id".execute(eventConsumer). "No beans of the origin were available"). 82 ORACLE.getOrderId()).getOrderId()). } public void handle(@Observes CoffeeBrewFinished event) { orderService.finishOrder(event. "barista".getOrderInfo(). }. //beyond CRUD / } public void handle(@Observes OrderFailedBeansNotAvailable event) { orderService.getOrderId().deliverOrder(event.cancelOrder(event.fire(ev). mes.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .startOrder(event.put("group. } public void handle(@Observes CoffeeBrewStarted event) { orderService. ev -> { logger. "order-handler"). events. eventConsumer = new EventConsumer(kafkaProperties.info("firing = " + ev).getOrderId()). I make use of event topics that are consumed in so-called consumer groups. and scalable event hub that delivers events to the services involved. The event producer. publishes the events to Kafka: @ApplicationScoped public class EventProducer { private Producer<String. CoffeeEvent> producer. In this case.stop(). shown in the following code. } } Integrating Apache Kafka Apache Kafka serves as a reliable. I conigure Kafka to deliver the events reliably once in every consumer group. @Inject Properties kafkaProperties. persistent. @PostConstruct private void init() { 83 ORACLE.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . By coniguring the same group for all event handlers. I ensure that only one instance processes an event. @Inject Logger logger. //beyond CRUD / } @PreDestroy public void closeConsumer() { eventConsumer. put("transactional. } public void publish(CoffeeEvent event) { ProducerRecord<String. UUID. They ensure that an event has been sent reliably before the client call returns.toString()). logger. } catch (ProducerFencedException e) { producer.commitTransaction().COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . producer.close().abortTransaction().randomUUID(). 84 ORACLE.beginTransaction(). producer = new KafkaProducer<>(kafkaProperties). try { producer. //beyond CRUD / kafkaProperties. } } The following code uses transactional producers that were introduced in Kafka version 0.11. } catch (KafkaException e) { producer. event).initTransactions(). producer.send(record).info("publishing = " + record).id".close(). producer. } } @PreDestroy public void close() { producer. CoffeeEvent> record = new ProducerRecord<>("order". The event con- sumer ininitely consumes new Kafka events and passes them to a functional Consumer. CoffeeEvent> records = consumer.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .close(). String.poll(Long. public EventConsumer(Properties kafkaProperties. private final AtomicBoolean closed = new AtomicBoolean().MAX_VALUE). Consumer<CoffeeEvent> eventConsumer. } } private void consume() { ConsumerRecords<String.get()) { consume(). topics) { this.eventConsumer = eventConsumer. CoffeeEvent> consumer. } @Override public void run() { try { while (!closed.. private final Consumer<CoffeeEvent> eventConsumer. 85 ORACLE. consumer. //beyond CRUD / public class EventConsumer implements Runnable { private KafkaConsumer<String.subscribe(asList(topics)).. consumer = new KafkaConsumer<>(kafkaProperties). } } catch (WakeupException e) { // will wake up for closing } finally { consumer. commitSync(). @Inject 86 ORACLE.accept(record. This event consumer is started from both the event handler and the updating consumer.wakeup(). @Resource ManagedExecutorService mes. } } After an event has been processed.set(true). CoffeeEvent> record : records) { eventConsumer. @Inject Properties kafkaProperties. Both are then responsible for iring the CDI events.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . //beyond CRUD / for (ConsumerRecord<String. I commit to the consumption by calling commitSync. See the OrderEventHandler deinition shown earlier and the following OrderUpdateConsumer: @Startup @Singleton public class OrderUpdateConsumer { private EventConsumer eventConsumer. consumer.value()). } consumer. } public void stop() { closed. }. "order-consumer-" + UUID.randomUUID()). they connect to their corresponding Kafka topics and ask for all the undelivered events in their consumer group.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . When these services start. ev -> { logger.fire(ev).put("group.execute(eventConsumer). //beyond CRUD / Event<CoffeeEvent> events. } @PreDestroy public void close() { eventConsumer.stop(). mes.id". For the updating consum- ers.info("firing = " + ev). the updating consumer group that has the matching ID applies the events—for 87 ORACLE. @Inject Logger logger. "order"). } } To ensure that the consumers are managed correctly. events. unique group IDs are generated to ensure that every service gets all events. To update the domain object representations to the latest state. I use Java EE’s managed executor service to run the consumers in threads managed by the application server. @PostConstruct private void init() { kafkaProperties. eventConsumer = new EventConsumer(kafkaProperties. For the full example applica- tion. it’s advisable to go with monolithic. this approach is no silver bullet. see the scalable-cofee-shop project on GitHub. serving in the JSR 370 and JSR 374 Expert Groups. As I mentioned before. If the situation does not require the scalabil- ity of event-driven architectures. consistent applications instead. CQRS introduces some overhead. He participates in the Java Community Process (JCP). When not working with Java. //beyond CRUD / example. which certainly is avoidable in most enterprise appli- cations. eventually consistent systems. An application that solely requires the beneits of event sourcing can be based on this approach while still using a relational database and consistent use cases. Daschner is also a heavy user of Linux and container technologies such as Docker. he loves to travel. in the CoffeeOrders—that occurred since the very beginning. Conclusion CQRS provides a useful alternative to the traditional CRUD-based way of building enterprise applications by combining the beneits of event sourcing and event-driven architectures to build scalable.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . </article> Sebastian Daschner (@DaschnerS) is a Java Champion who works as a consultant and trainer. Of course. 88 ORACLE. I’m using only in-memory storage without persistent snapshots. Push a Button Move Your Java Apps to the Oracle Cloud Same Java Runtime Same Dev Tools Same Standards Same Architecture … or Back to Your Data Center . As is so often the case. but they lack a deeper understanding of the underlying principles that would lead to writing better code. I try to pick topics that invite a deeper understanding of the conceptual background of a language construct. So. In such a case. A Little Background on Inheritance Inheritance is straightforward to understand in principle: a class can be speciied as an exten- sion of another class. They have all ields deined in either subclass or superclass and PHOTOGRAPH BY JOHN BLYTHE also all methods from both. creating bet- ter structures. //new to java / The Evolving Nature of Java Interfaces Understanding multiple inheritance in Java MICHAEL KÖLLING I n the occasional “New to Java” series. Java interfaces are often just such a topic. I assume that you have a basic understanding of inheritance. the story of these features starts with some quite simple and elegant ideas that lead to the deinition of concepts in early Java versions. they can use it in many situations. 90 ORACLE. and the class it’s extending is called the superclass. Java interfaces are closely related to inheritance. This challenge led to the introduction of default methods in Java 8. Often. so good. real-world problems. novice programmers have a work- ing knowledge of a concept—that is. as are the extends and implements keywords. I will discuss why Java has two diferent inheritance mechanisms (indicated by these keywords). and what various tasks interfaces can be used for. and the story gets more com- plicated as Java advances to tackle more-intricate. and making better decisions about when to use a given construct. In this article.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . Objects of the subclass have all the properties of both the superclass and the subclass. So far. the present class is called a subclass. how abstract classes it in. which muddied the waters a bit. especially because standard Java inheritance mixes them together. In that sense. Both the code and the type are inherited. however. ideas. and I can use it for a variety of other tasks. as I explain shortly). but it is not the only way a language can be designed. It is useful to separate these two ideas conceptually. Let me give you an example: PhD students at my university also work as instructors. When I create a subclass (using the extends keyword). but they also have the type Person. but very diferent. I can create variables of that type. I can use it to separate speciication from implementation. //new to java / Inheritance is. have a room number. every class I deine also deines a type: as soon as I have a class. I can use inheritance to reuse some code I have writ- ten before. Inherited methods are available to be called (I’ll refer to this as “the code”). and objects of the subclass can be used in places where objects of the superclass are expected (thus. If Student is a subclass of Person. for example. then objects of class Student have the type Student. I can use it for subtyping and dynamic dispatch. they are like faculty (they are instructors for a class. Other programming languages allow inheriting the code without inheriting the type (such as C++ private inheritance) or inheriting the type without inheriting the code (which Java also supports. In Java. Type Inheritance Versus Code Inheritance Two main capabilities that inheritance provides are the ability to inherit code and the ability to inherit a type. Multiple Inheritance The next idea entering the mix is multiple inheritance: a class may have more than one super- class. the equivalent of the Swiss Army knife in programming: it can be used to achieve some very diverse goals.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . the subclass creates a subtype). the subclass inherits both the code and the type of the superclass. Let’s look at an example. The decision to link type inheritance and code inheritance in Java is a language design choice: it was done because it is often useful. a payroll 91 ORACLE. These are all important. It is necessary to understand these diferences to get a good feel for inheritance and interfaces. A student is a person. I can use it to specify a contract between diferent parts of a system. However. a PhD student will have the attributes of both students and faculty. Now. the language becomes more complicated if it allows multiple inheritance. because that introduces new problems: What if both superclasses have ields with the same name? What if they have methods with the same signature but diferent implementations? For these cases. should the class at the bottom (PhDStudent) have one copy of this ield or two? It inherits Person Faculty Student Faculty Student PhDStudent PhDStudent Figure 1. An example of multiple inheritance Figure 2. it gets worse. This is where a class (PhDStudent) has two superclasses (Faculty and Student). In practice. in this case). which in turn have a common super- class (Person). consider this question: If there is a ield in the top-level superclass (Person. PhDStudent is a subclass of both Faculty and Student. But they are also students: they are enrolled in a course. An example of diamond inheritance 92 ORACLE. //new to java / number. and so on. This way. how- ever.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . and so on). have a student ID number. I need language constructs that specify some solution to the problem of ambiguity and name overloading. I can model this as multiple inheritance (see Figure 1). Conceptually this is straightforward. Diamond Inheritance A more complicated scenario is known as diamond inheritance (see Figure 2). The inheritance graph forms a diamond shape. Java needs to be able to specify types without specifying code. but allow multiple have two: a student ID and a faculty/payroll ID that inheritance for types. If the ield in question pragmatic solution: allow only single is. Type Inheritance to the Rescue When you think about these problems carefully. Languages that allow full multiple inheritance need to have rules and constructs to deal with all these situations. //new to java / this ield twice. but multiple type inheritance causes no problems. This fact is coupled with another observation: multiple code inheritance is not terribly important. the person’s family name. because you can use delegation (using a reference to another object) instead. 93 ORACLE. then you want only one (the PhD student has only one family name. In short. Interfaces To make it possible to have diferent rules for types and code. Interfaces specify a Java type (the type name and the signatures of its methods) without specifying any implementation. however. even though it is inherited from both superclasses). but multiple subtyping is often very useful and not easily replaced in an elegant way. You can leave out the modiiers (public static final for constants and public for methods)—they are implicitly assumed. No ields and no method bodies are speciied. say. might be a diferent number. Interfaces can contain constants. That is what a Java interface does. an ID number. That is why the Java designers arrived at a pragmatic solution: allow only single inheritance for code. and these rules are complicated. once via each of its inheri- tance branches. Multiple code inheritance is messy. things can become very messy. If the ield is.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . maybe a PhD student should inheritance for code. you realize that all the problems with multiple inheritance are related to inheriting code: method implementations and ields. The Java designers arrived at a The answer is: it depends. but allow multiple inheritance for types. after all. And I can now have diferent rules concerning mul- tiple inheritance: Java permits multiple inheritance for types (interfaces) but only single inheri- tance for classes (which contain code). there are other kinds of active objects in your simulation. You may then have a central collection in your program—say. in this case. traic lights. Actor. and so on.. a List—that holds all the actors: private List<Actor> actors. } Your Car class can then implement this interface: class Car implements Actor { public void act() { . 94 ORACLE. such as pedestrians.. could be an interface with an act method: public interface Actor { void act(). in which I inherit both the type and the code. or I can inherit a type only (using implements) by inheriting from an interface. Apart from cars. Suppose you are writing a traic simulation. Benefits of Multiple Inheritance for Types The beneits of allowing the inheritance of multiple types—essentially of being able to declare that one object can be viewed as having a diferent type at diferent times—are quite easy to see. trucks. and in it you have objects of class Car.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . //new to java / This arrangement provides me with two types of inheritance in Java: I can inherit a class (using extends). In this case. if the Car objects are part of all three lists (they act. focusing on diferent aspects to group them with other similar objects or to treat them according to a certain subset of their possible behaviors. and the objects to be saved might. Drawable.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . But imagine now that there is also a list of all objects to be drawn on screen (which is not the same as the list of actors. and allowing multiple supertypes enables you to view a sin- gle object (the car. be a diferent list. //new to java / } } Note that. including the signature of the act method. So far.. Serializable . To be saved. You might also want to save a simulation to permanent storage at some point. they need to be of type Serializable: private List<Serializable> objectsToSave. the class Car can be deined to implement all three interfaces: class Car implements Actor. because some actors are not drawn. but no code. in this case) from diferent perspectives. Situations like this are common.. and some drawn objects are not actors): private List<Drawable> drawables. because Car inherits only the type. they are drawn. again. Java’s GUI event-processing model is built around the same idea: event handling is achieved via event listeners—interfaces (such as ActionListener) that often just implement a single method—so that objects that implement it can be viewed as being of a listener type when necessary. this is just single inheritance and could have been achieved by inheriting a class. and they should be saved). it must itself supply the code to implement the type (the implementation of the act method) before you can create objects from it. 95 ORACLE. since version 5. the Actor interface could be an abstract class instead. Abstract classes sit halfway between classes and interfaces: they deine a type and can contain code (as classes do). If you are tempted. Multiple inheritance is for interfaces only. Serializable. These interfaces are known as marker interfaces. As I stated before. turning them all into abstract classes does not work. Serializable . but maybe it contains some other code that is common to all actors. There is little reason today to use marker interfaces in Java. because it is common to wonder how they relate to interfaces. which were introduced in Java 8. The act method itself might be abstract (because it is diferent in each speciic actor and there is no reasonable default). You can think of them as partially implemented classes with some gaps in them (code that is missing and needs to be illed in by subclasses).COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . If I want several of my interfaces to contain code. //new to java / Abstract Classes I should say a few words about abstract classes. I can write Actor as an abstract class. mentioned previously.. is such an interface. but not implemented. They mark certain classes as possessing a spe- ciic property. In this case. Java. and their purpose is more closely related to providing metadata than to imple- menting a type or deining a contract between parts of a program. though: default methods. look instead at using annotations. Java allows only single inheritance for classes (that means only one class can be listed after the extends keyword). In my example above. has had annotations. I’ll get to them shortly. 96 ORACLE. Empty Interfaces Sometimes you come across interfaces that are empty—they deine only the interface name and no methods. and the inheritance declaration of my Car class would look like this: class Car extends Actor implements Drawable. but they can also have abstract methods—methods that are speciied only. Cloneable is another.. which are a better way of providing metadata. There is a way out. In my explanation of the issues. but a system for practical use. //new to java / A New Dawn with Java 8 So far. But how do you evolve an interface without breaking all the exist- ing code that uses this interface? Imagine you have an interface MagicWand in your existing library: public interface MagicWand { 97 ORACLE. This is because Java 8 adds functionality that contradicts some of the earlier design decisions of the language (such as “only single inheritance for code”). Evolving Interfaces One problem in developing Java 8 was how to evolve interfaces. how- ever. because understanding the justiication for the combination of features as they are today is pos- sible only in light of this history. but with some subtle diferences. Default methods and static methods in interfaces are two mechanisms that made progress possible in Java 8. I have taken you down the historical path—explaining the pre-Java 8 situation irst and now adding the newer Java 8 features. you must ind ways to evolve and extend your language without breaking everything that has been done before. If the Java team were to design Java from scratch now. Java 8 added lambdas and sev- eral other features to the Java language that made it desirable to adapt some of the existing interfaces in the Java library. The Java language is. As I will show in a moment. I have purposely ignored some new features that were introduced with Java 8. And in the real world. not foremost a theoretical exercise. they would not design it in the same way.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . interfaces in Java 8 have been extended so that they become more similar to abstract classes. Arguing the diference between and justiication for the exis- tence of interfaces and abstract classes. I did this on purpose. becomes quite tricky. for instance. and if breaking backward compat- ibility were not a problem. which makes explaining the relationship of some constructs quite diicult. So. then all classes that previously implemented this interface break. there are some other approaches that you could try. which I do not discuss here. which I discuss now. and they have a full method body: public interface MagicWand { 98 ORACLE. This is done using default methods and static methods. but these have their own problems. at irst glance. and you would like to add a really useful new method: public interface MagicWand { void doMagic(). But you now come up with some really great new functionality.) Java 8 came up with a clever trick to get the best of both worlds: the ability to add to existing interfaces without breaking existing code. Default Methods Default methods are methods in interfaces that have a method body—the default implementa- tion. it seems you are stuck: either you break existing user code (which you don’t want to do) or you’re doomed to stick with your old libraries without a chance to improve them easily. } This interface has already been used and implemented by many classes in many projects. } If you do that. such as extending interfaces in subinterfaces. void doAdvancedMagic(). (In reality. //new to java / void doMagic(). because they are required to provide an implementation for this new method. They are deined by using the default modiier at the beginning of the method signature.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . There still are some diferences (for instance. What About the Diamond Problem? As you can see. As always.. //new to java / void doMagic(). // some code here } } Classes that implement this interface now have the chance to provide their own implementa- tion for this method (by overriding it). while new code can use this new functionality. So what is the situation now? As usual. Static Methods Interfaces can now also contain static methods with implementations. abstract classes can have instance ields. the Java designers devised the following sensible and practical rules to deal with these problems: 99 ORACLE. the public modiier may be left out. because all methods and all constants in interfaces are always public. but these diferences support a central point: since the release of Java 8. So. although the syntax is diferent. Both can contain abstract methods and methods with implementations..COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . whereas inter- faces cannot). mostly related to inheriting multiple times and to name clashes. in which case they receive the default implementation from the interface. or they can completely ignore this method. Old code continues to work. These are deined by using the usual static modiier at the beginning of the method signature. default void doAdvancedMagic() { . you have multiple inheritance (via interfaces) that can contain code! At the beginning of this article I pointed out how the Java designers treaded very carefully to avoid multiple code inheritance because of possible problems. when writing interfaces. abstract classes and interfaces have become quite similar now. deining types for dynamic dispatch. they are less likely to be used in application code. But here Java chooses a much more pragmatic solu- tion than some other languages: instead of deining a new language construct to deal with this. ■■ Inheriting from diferent interfaces multiple default methods with the same signature and diferent implementations is a problem. They are very often useful in your code. because they are preixed by the interface name when they are used. Java just tells you. </article> [An earlier version of this article ran in the September/October 2016 issue of Java Magazine. //new to java / ■■ Inheriting multiple abstract methods with the same name is not a problem—they are viewed as the same method. you should make sure you understand their behavior well. the Java libraries now make extensive use of them. ■■ Diamond inheritance of ields—one of the diicult problems—is avoided. two educational programming environments. ■■ Inheriting static methods and constants (which are also static by deinition) is not a problem. and he is the lead developer of BlueJ and Greenfoot. it’s your problem. In other words. Careful use of interfaces can signiicantly improve the quality of your code. Kölling is also a Distinguished Educator of the ACM. The new interface features in Java 8. the compiler just reports an error. such as default methods. “Don’t do this.] Michael Kölling is a Java Champion and a professor at the University of Kent. because interfaces are not allowed to contain ields that are not constants. England. so make sure you know what they do.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . including for deining contracts between diferent parts of the program. They are useful in many situations. separating the deinition of a type from its implementation. He has published two Java textbooks and numerous papers on object orientation and computing education topics.” Conclusion Interfaces are a powerful feature in Java. are most useful when you write libraries. —Ed. so their names do not clash. However. 100 ORACLE. and allowing for multiple inheri- tance in Java. which is the certiication test for developers who have been certiied at a basic level of Java 8 programming knowledge and now are looking to demonstrate more-advanced expertise. so you’ve already been seeing the beneit of his work. Given this code: public class OneValue { private final int x. of course. Questions marked “advanced” come from the 1Z0-809 Programmer II exam. Those marked “intermediate” correspond to ques- tions from the Oracle Certiied Associate exam.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . //ix this / Quiz Yourself More intermediate and advanced test questions SIMON ROBERTS I f you’re a regular reader of this quiz. MIKALAI ZAIKIN Question 1 (advanced). Change 2. I’ll begin covering Java 9 in future columns. which contains questions for a preliminary level of certiication. These questions rely on Java 8. Add to the class as follows: public OneValue() { 101 ORACLE. } Consider these possible changes: Change 1. He’s been working on these questions with me for some time now. I’d also like to welcome Mikalai Zaikin to this column as a coauthor. and I will make that transition quite clear when it occurs. you know that these questions simulate the level of dif- iculty of two diferent certiication tests. Change the declaration of x as follows: private final int x = 99. Question 2 (advanced). 1. 8. 102 ORACLE. } } B. public Immut1(String n) { this. The code compiles if change 2 is done. The code compiles if change 1 is done. Add to the class as follows: private void setX(int x) { this. B. 8. A. //ix this / x = 100.x = x. The code compiles as it is. The code compiles if change 3 is done. D. 2. public class Immut2 { final int[] data = { 1.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . } Which are true? Choose two. 13 }. The code compiles if change 1 and change 2 are both done. A. Which of the following classes produce immutable objects? Choose two. 5. String name. 1. C. } public OneValue() { setX(100). E. 2. 5. final String name. 3. } Change 3. 13 }. 3. public class Immut1 { final int[] data = { 1.name = n. } } 103 ORACLE. } } E. } } D. public class Immut3 { private int x.name = n. } } C. } public String get(int idx) { return ls.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .get(idx).unmodifiableList(Arrays.. strings) { ls = Collections. "Sheila"). public Immut4() { ls = Arrays. "Jim".x = x.get(idx). //ix this / public Immut2(String n) { this. public class Immut4 { private List<String> ls.asList("Fred".asList(strings)). public Immut3(int x) { this. } public String get(int idx) { return ls.. public Immut5(String. public class Immut5 { private List<String> ls. //ix this / Question 3 (intermediate). // line n1 Which is true? A. StringBuilder sb2 = new StringBuilder("Hello"). Given this method: public final void doStuff(int val) /* point A */ { if (val < 0) throw new NullPointerException(). Insert the following at point A: throws IOException E. 104 ORACLE. Insert the following at point A: throws NullPointerException Question 4 (intermediate). SQLException D. Insert the following at point A: throws Exception B.println(sb + sb). OutOfMemoryError C. Insert the following at point A: throws IOException. StringBuilder sb = new StringBuilder("Hello"). if (val < 2) throw new OutOfMemoryError(). the following fragment: System. OutOfMemoryError. Given this: String s = "Hello". Placed at line n1. if (val < 1) throw new IOException(). } Which of the following is best? A.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .out. Insert the following at point A: throws NullPointerException. prints this: Differ 105 ORACLE.out. the following fragment: CharSequence val = sb. //ix this / prints this: HelloHello B. System. prints this: true C.equals(s)?sb:"Differ").println(sb.println(sb. Placed at line n1. System.out.println(val). prints this: Hello E. the following fragment compiles successfully: String val = sb.equals(sb2)). Placed at line n1.equals(s)?sb:"Differ". Placed at line n1. Placed at line n1.println(val). D.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 .equals(s)?sb:"Differ".out. the following fragment: System. the following fragment: System.out. the change fails. option B is correct.3. Java Language Speciication section 8. and option C is correct. exactly once. Note that the ield as declared is termed a “blank inal” (the terminology used in the Java speciication paragraph above) and as such. or a compile-time error occurs. However. 106 ORACLE. the default assignment to zero that is implicit for all object members does not satisfy the requirement. This change.2 says this about inal ields: “A blank inal instance variable must be deinitely assigned at the end of every constructor of the class in which it is declared. this change works. x is deinitely assigned even before any constructor runs. option E is also incorrect. because it’s possible for it to be invoked after the object has been initialized. Because the blank inal is deinitely assigned. Because this fails to compile. because this would result in an attempt to perform two assignments to the variable x. Change 3 suggests adding a constructor that might seem functionally equivalent to the one proposed in change 2. This tells you immediately that option A must be incorrect.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . Therefore. Performing both change 1 and change 2 also fails. The private method that attempts to assign the value to x will not compile. therefore. would result in exactly one constructor and causes that constructor to unconditionally assign a value to x. Therefore. //ix this / Answers Answer 1. and the Java speciication demands exactly one assignment. because in the original code presented in the question there is no assignment to the ield.1. option D must be incorrect. Change 1 assigns a value to x as part of its declaration and. made in isolation. The correct answers are options B and C. before the end of the only constructor. in this case.” This means that the inal ield x must receive exactly one explicit assignment. Change 2 adds a simple constructor that initializes the value of x. which must happen before the constructor is complete. so that ield’s value can never be changed. data can never refer to any array other than the one with which it’s initialized. Now. An object is immutable if no syntactically permissible interaction with it by external code can change its state after construction. the values in the data array are actually mutable by any code in other classes in the same package. Hence. In option B. Strings themselves are immutable. which might have unexpected consequences. it has some value in concurrency that and it also dares to stray into that troublesome is not part of this discussion. it must refer to the string object that’s passed into the constructor. particularly in concurrent systems). the contents of final int [] data can. In particu- purpose of Java’s exception mechanism. This is because the final keyword prevents the value of data—which is a pointer— from being modiied. So. Of course. //ix this / Answer 2. However. before analyzing this question. Therefore. In particular. lar. it should almost certainly be used anyway. although you already know option A is incorrect based on the string ield). the value remains the same. the length of arrays can never change after they are created.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . but their contents can be changed. so it’s a simple matter for any other class that has access (that is. rather than being private. although you’ll see that the final keyword is not suicient to render This question investigates the rules and everything it touches unalterable. 107 ORACLE. once it is created. Literally. The correct answers are options C and D. be changed (and actually. too. be aware that if you decide to create classes that yield immutable objects (which is a design style that can reap signiicant rewards in terms of correct- ness.” of immutability through relection. Also keep in territory of asking what’s “best” rather than mind that it’s possible to break many forms merely what’s “correct. the String name ield has been marked inal. it cannot be mutated. the ields have default accessibility. Therefore. option B is incorrect. and no code within the class ever makes any such change either. any other class in the same package) to mutate the value of the String name to point to a diferent string. option A is incorrect. you should do a better job than the examples shown here. in fact. In option A. it could be changed in option A. so even though it’s accessible to other members of the package. you would know the object is immutable. noninal ield. So. any changes made to that array will be relected in the list. //ix this / In option C. even though the ield is not marked inal. Therefore. there is a single ield: int x. the objects are not reliably immutable and option E is incorrect. Because it’s private. which is a utility that describes itself as creating a “structurally immutable list”—which sounds promising. and option C is correct. The variable ls is initialized to refer to a list created by the Arrays. which puts a proxy wrapper around the object. You permitted in the context of the overridden method. Because of this. option D is correct. ls.unmodifiableList. The ield is private but not inal. you again see a private.”) Because of this. Also. In option D. But to counter that. the list will not allow the addition or removal of elements. it’s List<String> ls. and with primitive types. if the caller of the constructor chooses to provide an explicit String [] as its argument.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . have a variable. so that any attempt to modify the list will throw an exception. the “value” really is the value being represented. you know that nothing changes the value of ls to make it refer to a diferent list object. However. the list cre- ated by Arrays. The value of the ield is initialized with a copy of the value passed to the constructor. This time. Therefore. not the “value of the reference. and nothing outside the class ever has a copy of the reference value in ls. Surely this must be immutable. 108 ORACLE. instances of this class are immutable. If you can be sure that the list that ls refers to cannot be altered in any way. it turns out that the list that’s created uses the provided array as its backing storage. It’s prohibited for an overriding method to Therefore. right? Well. this list is wrapped in Collections. changes to the original variable that was passed as an argument to the constructor do not afect the value of x. declare checked exceptions that were not already Option E is a little more subtle.asList actually honors attempts to reassign any given element of the list. (All arguments in non- remote Java method invocations are passed by value. which is identical to the one described in option D. no code in the class ever changes the value of x after the object is constructed.asList method. nothing will ever change the contents of the list or point the variable at a diferent list. It’s pretty clear that any situation that doesn’t even compile cannot be considered satisfactory. Therefore. we hope to make a good case for that value judgment.get(0)). //ix this / If you want to examine this efect. Options B and E fail on that point. Therefore. System. Immut5 i5 = new Immut5(names). the question is really asking what excep- tion declaration would best suit this method. The correct answer is option D. so as long as some of the options would compile they must be “better than” any that do not. options B and E are incorrect.get(0) " + i5.println("i5.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . the appropriate point for the syntax that declares such information is marked /* point A */. 109 ORACLE.get(0) " + i5. and while we are happy to include this question because it creates a useful discussion—both about Java’s exception mechanism and about how to evaluate a judgment like this—we doubt that this question would survive unchanged in the real exam. the method must declare something that encompasses that exception. System. names[0] = "Anthony". In particular. In this question. try running this code: String [] names = {"Tony".” However.get(0)).out. Answer 3. If the method might throw any checked exceptions.out.) For convenience. we’ll simply use the term unchecked exceptions to include errors that are not parents of IOException. not of Exception.println("i5. so at a minimum. The irst point is that Java distinguishes checked exceptions from unchecked exceptions and errors. it must carry a declaration that announces that. "Jane"}. In this case. Consider the issue of compilation irst. (Note that OutOfMemoryError falls into the category of “unchecked. This question investigates the rules and purpose of Java’s exception mechanism. a method that might throw a checked exception must announce this in that method’s signature. and it also dares to stray into that troublesome territory of asking what’s “best” rather than merely what’s “correct.” although it’s a subclass of Throwable. because they declare unchecked exceptions. the only checked exception that is potentially thrown is the IOException. the remaining options all declare either IOException or a parent class of IOException. As a result. it’s clear that option C. so how can you choose the “best” option among these? When you declare an exception in a throws clause. Further. you impose an obligation on the caller of the method. By the same arguments. There’s another small point to consider as part of this discussion. //ix this / However.” Therefore. Why would that make any diference? It’s certainly a tenuous point in this case. an abstract method in an inter- face declares a fairly general exception (consider the close() method in the AutoCloseable inter- face. which reports one unchecked exception (OutOfMemoryError) with a checked exception that cannot arise. the throws clause is a form of description of the type of problems that can arise when calling the method. Because of this. Given that such a method cannot possibly throw any exceptions because it doesn’t have any implementation. which throws Exception). the caller must do something about the exception. options A. Often. making it harder for the caller to know how to respond if an exception is reported. why would this be? The answer is that it’s prohib- 110 ORACLE. On this basis. which simply (and vaguely) reports that an Exception might arise. arise. and option D is the correct answer. The question mentions that the method is inal.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . which gets directly to the point of reporting the single checked exception that could arise from the method. To be more general or to Testing equality between diferent mention irrelevant exceptions might place an addi- tional burden on the caller by creating a perceived types almost always returns false requirement to handle situations that don’t in fact regardless of the contents. Also. you can also see that option A. It’s important to note that a throws clause that mentions a parent exception class is suicient to encompass any child classes. is also less helpful than option D. option C is incorrect. is unlikely to qualify as “best. but it helps justify the “best” value judgment. you can conclude that option A is incorrect. additional generality will likely have the efect of hiding the real problem that might arise. These points both suggest that a throws clause should be as speciic as possible. C. and D all allow the code to compile correctly. This means that if a method is expected to be overridden. but if the reference turns out to refer—at runtime—to an implementation that does throw that checked exception.) However. it would have been much harder to make a convincing case that option C was not the “best” choice (because it allows additional lexibility). brings up a third fundamental rule: in Java any data type can be converted into a String. declaring throws SQLException is just a source of confusion. it will be converted into one—and that. it would break the protections provided by checked exceptions. they’re both instances of the interface CharSequence—neither operand is a String. Therefore. because the method does not throw SQLException nor is it possible that any overriding method might do so. Another fundamental rule is that when a + operator has a String type as an operand. in this case. it’s not unreasonable to declare it as throwing some checked exceptions that simply don’t arise in its current form. (Admittedly. option A is incorrect. if the other operand is not a String. Because of this. and the compiler would let you call a method on it without handling a particular checked excep- tion. But as it is. the code uses the + operator with two operands that are StringBuilder objects. allowing an overriding method to do something not permitted for the overridden method would break the Liskov Substitution Principle. the conversion isn’t always very helpful. and in this speciic case. This question investigates several aspects of StringBuilder and its relationship with String. although both operands represent “text” in the general sense—indeed. because it attempts to use the + operator with illegal arguments. includes the methods that implement interface abstract methods) to declare checked exceptions that were not already permitted in the context of the overridden method. Without this restriction.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . but it’s deinitely legal. Answer 4. One of Java’s “special case” rules is that the only allowed operator overloading is the language- deined ability to concatenate String types using the + operator. Had the method not been inal. the code fails to compile. you would have efectively cheated the checked exception mechanism. you could have a reference of a parent type. Generally. //ix this / ited for an overriding method (which. of course. In option A. of course. 111 ORACLE. The correct answer is option E. In option E. they are not assignment- compatible with one another. they’re both subclasses of Object. In these options. This now forms a legal. However. relatively few of the core Java API classes implement a useful equals method. and option B is incorrect.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . that’s not at all the case. you have two StringBuilders that contain the same text. the intermediate variable val has been removed and the ternary expression is the argument to the println call. indeed.equals(s) will evalu- ate to false. because the arguments are of difering types. This turns out to be a pretty simple rule. look at StringBuilder. String and StringBuilder are diferent types on independent branches of the inheritance tree. the test in the ternary expression sb. compilable fragment. and they both implement the CharSequence interface. The inal three options all hinge on related points. In this case. they also have elements of a shared type hierarchy. and StringBuilder is not one of them. the ternary expression as a whole evaluates to the third operand. and you’ll see the API docs deine how it tests for identical character sequences. the fragment in option B actually prints false. The type of such an expression cannot be String. However. In option D. it’s easy to assume that the two objects will test as equal.” Of course. But. it’s up to the compiler to ind a suitable type 112 ORACLE. and StringBuilder does not handle that. and the fragment prints Differ. in this question. Given that the test evaluates to false. the default equals method deined by Object tests to see if two ref- erences refer to the same object in memory. option C is incorrect. the type of the variable val has been changed to CharSequence. However. Look at String’s equals method. option D is incorrect. Therefore. it must be some common parent of both arguments. too. As a result. However. The way you can determine this is by looking at the documentation of the class. Testing equality between diferent types almost always returns false regardless of the contents (with some exceptions—take a look at the API-documented requirements for the equals methods in the List and Set implementations). the only mention of the equals method is that it’s “inherited from java. a ternary expression has String and StringBuilder as the two option val- ues. Because of this. In this situation. Therefore.lang. the attempt to assign the result of the ternary expression to the String variable val in option C will cause a compilation failure. As such. //ix this / Option B considers equality testing.Object. but our excuse is that by using it here. both String and StringBuilder are. He created the Sun Certiied Java Programmer and Sun Certiied Java Developer exams. He wrote several Java certiication guides and is currently a freelance educator who publishes recorded and live video training through Pearson InformIT (available direct and through the O’Reilly Safari Books Online service). We doubt you’ll come across it in the real exam. Mikalai Zaikin is a lead Java developer at IBA IT Park in Minsk. option E is correct. Belarus. the code compiles successfully. Therefore.equals(s) still evaluates to false and the output that is printed is Differ—as it was in option D. Of course. However. //ix this / for the expression. We hope you’ll forgive the indulgence! </article> Simon Roberts joined Sun Microsystems in time to teach Sun’s irst Java classes in the UK. we were able to make the example a little more interesting and. As a side note. consequently. he has helped Oracle with development of the Java certiication exams. 113 ORACLE. During his career.COM/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . the CharSequence interface isn’t explicitly mentioned in the exam objec- tives. and it doesn’t really matter if it chooses Object or CharSequence. including three editions of the famous Sun Certified Programmer for Java study guides by Kathy Sierra and Bert Bates. Either is a legitimate argument to the println method and. and he has been a technical reviewer of several Java certii- cation books. the expression sb. He remains involved with Oracle’s Java certiication projects. perhaps. and this interface is an aspect of both. teach something useful. on preparing an article.com. USA. Article Proposals Redwood Shores. Please contact us with your ideas While it will have no inluence on our Unless you speciically tell us that your at javamag_us@oracle. CA 94065.com and we’ll decision whether to publish your article correspondence is private. be gratefully accepted by our staf at the Editor section. unusual but useful Where? We welcome your comments. tant to share with us or our readers. at [email protected]/JAVAMAGAZINE ////////////////////////////////// JANUARY/FEBRUARY 2018 . MS OPL 3A-3133. Oracle Corporation. and most other Comments and article proposals should tions. We welcome article proposals on all Customer Service topics regarding Java and other JVM If you’re having trouble with your sub. would enjoy are of great interest to us. topics that hard-core Java programmers be sent to our editor. who will do what. Java Magazine in Japanese source or those bundled with the JDK). Andrew Binstock. correc. please contact the folks at Download area for code and We also are interested in proposals for java@omeda. 114 ORACLE. too. other items articles on Java utilities (either open ever they can to help.com. 500 Oracle Parkway. algorithms. cookies and edible treats will the right to publish it in our Letters to send you our nifty writer guidelines. and any other thoughts you feel impor. scription. opinions on topics we’ve covered. //contact us / magazine By and for the Java community Comments Finally. we reserve give you our thoughts on the topic and or letter. World’s shortest subscription form languages. as well as the JVM itself. programming techniques. which will give you more information Java Magazine.
Copyright © 2024 DOKUMEN.SITE Inc.