WHAT’S NEW IN NASHORN 34 | INCUBATING HTTP/2 39 | LANGUAGE QUIZ 47

JULY/AUGUST 2017

magazine

By and for the community

11 17 21 28 NINE NEW MIGRATING ENHANCEMENTS JSHELL: FEATURES FROM JAVA 8 TO COLLECTIONS, THE NEW OF JDK 9 TO JAVA 9 STREAMS, AND REPL ITERATORS

ORACLE.COM/JAVAMAGAZINE //table of contents /

17 21 28 34 39 MIGRATING JAVA 9 CORE JSHELL: NASHORN WORKING FROM JAVA 8 LIBRARY READ- JAVASCRIPT WITH THE TO JAVA 9 UPDATES: EVALUATE- ENGINE IN NEW HTTP/2 By Trisha Gee COLLECTIONS PRINT LOOP JDK 9 CLIENT Step-by-step AND FOR THE JAVA By Jim Laskey By Gastón Hillar work can lead to STREAMS PLATFORM Handy additions An incubating the adoption of By Raoul-Gabriel By Constantin and support technology in all or some of the Urma and Richard Drabo for ES6 make JDK 9 promises features as you Warburton Testing code Nashorn even to make HTTP need them. Collections, snippets is now more useful. communication Streams, and part of the JDK. a lot simpler. iterators have 11 all added new NINE NEW DEVELOPER capabilities. FEATURES IN JDK 9 By Simon Ritter There’s a lot more to this release than modules.

COVER ART BY I-HUA CHEN

03 05 47 38 From the Editor Letters to the Editor Fix This User Groups The noisy, successful undertaking of Comments, questions, suggestions, By Simon Roberts The London Java Community collaborative work: Delays in the delivery and kudos Our latest code quiz 55 of major releases such as JDK 9 are 06 16 common when community is valued. Contact Us Events Java Proposals of Interest Have a comment? Suggestion? Want to Upcoming Java conferences and events JEP 241: Remove the jhat Tool submit an article proposal? Here’s how.

01

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 EDITORIAL PUBLISHING Editor in Chief Associate Publisher and Audience Andrew Binstock Development Director Managing Editor Karin Kinnear +1.650.506.1985 Claire Breen Audience Development Manager Copy Editors Jennifer Kurtz Karen Perkins, Jim Donahue 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. Richard Merchán Register Now Senior Designer RESOURCES Arianna Pucherelli Oracle Products Designer +1.800.367.8674 (US/Canada) Jaime Ferrand Oracle Services Senior Publication Designer +1.888.283.0591 (US) Sheila Brennan Oracle Code Production Designer Kathy Cygnarowicz New One-Day, Free Event | 20 Cities Globally

Explore the Latest Developer Trends:

ARTICLE SUBMISSION • DevOps, Containers, Microservices & APIs If you are interested in submitting an article, please email the editors. SUBSCRIPTION INFORMATION • MySQL, NoSQL, Oracle & Open Source Databases Subscriptions are complimentary for qualified individuals who complete the subscription form. • Development Tools & Low Code Platforms MAGAZINE CUSTOMER SERVICE [email protected] • Open Source Technologies PRIVACY Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer • Machine Learning, Chatbots & AI that your mailing address or email address not be included in this program, contact Customer Service.

Copyright © 2017, Oracle and/or its affiliates. All Rights Reserved. No part of this publication may be reprinted or otherwise reproduced without permission from the editors. JAVA MAGAZINE IS PROVIDED ON AN “AS IS” BASIS. ORACLE EXPRESSLY DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ORACLE BE LIABLE FOR ANY Find an event near you: DAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN. Opinions expressed by authors, editors, and interviewees—even if they are Oracle employees—do not necessarily reflect the views of Oracle. developer.oracle.com/code The information is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of and/or its affiliates. Other names may be trademarks of their respective owners. Java Magazine is published bimonthly and made available at no cost to qualified subscribers by Oracle, 500 Oracle Parkway, MS OPL-3A, Redwood City, CA 94065-1600. 02

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //from the editor /

Level Up at Oracle Code

The Noisy, Successful Undertaking Step up to modern cloud development. At the of Collaborative Work Oracle Code roadshow, Delays in the delivery of major releases such as JDK 9 expert developers lead labs and sessions on PaaS, are common when community is valued. Java, mobile, and more.

Get on the list his issue of Java Magazine is all about the previous delays triggered a great sense of frustra- for event updates: Trelease of Java 9. When I was originally laying tion. Not for me. Sure, I would have loved to have go.oracle.com/oraclecoderoadshow out the editorial schedule, this special issue was the release and this magazine come out simulta- assigned to a slot in last year’s lineup. As many of neously, and certainly I would have liked to begin you know, that intended delivery date was post- the transition to the new version with a final poned until late July of this year, which is why release of the JDK. Those sentiments, I believe, you have this issue in your hands now. We antici- are universal in the community. pated—with excitement—that this issue and the However, what lets me abide the delay with- Java 9 release would occur simultaneously. out complaint is that it derives from collaboration But this happy scenario was thwarted by an with the community. As anyone who has served unexpected development: a disagreement within on industry committees can tell you, collaborative the Java Community Process (JCP) that pushed the work is difficult, noisy, and supremely frustrat- developer.oracle.com release back until late September of this year. ing. There is nothing quite like it, except perhaps For some in the Java community, this post- parenting. Yet despite the frustrations, there is a ponement and the fact that it came after several conviction held by all parties that it is better to #developersrule

PHOTOGRAPH BY BOB ADLER/THE VERBATIM AGENCY 03

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //from the editor /

work through the hard parts of the collabora- make innovations available on a predictable tion than to abandon the effort. We are all schedule. This new approach proposes publish- better served by the collaboration than by ing whatever technology is good to go when insisting on our own preferences. the announced date arrives. Georges Saab, vice The understanding of collective benefit president of development for the Java Platform has long driven Java’s history and is indisput- group at Oracle, states that this new approach ably integral to its success. It can be easy to will be adopted in post–Java 9 releases. It will forget that the development of Java and the mean less waiting for a single central feature JVM is itself a collaborative effort. The devel- to be ready before lesser improvements are opment work is done as open source in public shipped. Ironically enough, this strategy is repositories, and the discussions about feature possible now because of the modularity in Java 9 selection, code implementations, release dates, that can localize the effects of a given change. and other points of contention are held in pub- In sum, the delays of this release are the lic mailing lists. In fact, the recent decision necessary product of the open, collaborative regarding the new release date and the spe- model that underlies Java’s success. If you’re a cific reasons for the delay were all posted and supporter of open source and open collabora- replied to on public forums. guages or their preferred approach, but rather tion, then you surely recognize that such delays Now, let me ask you, do you know of any I’m trying to underscore how unique Oracle’s are a sacrifice that the process demands. In other language whose principal corporate approach with Java is.) that sense, it is the antithesis of releasing by sponsor assigns more than 100 engineers to I recognize that my acceptance of delay in unilateral fiat. Nonetheless, I am excited that work on the language and yet defers on matters the name of collaboration is borne of an insid- modularity makes possible future releases on a of release date to a community of partners? er’s view of Java community operations. Many defined schedule while maintaining the com- There are only three companies outside of Java developers have no interest in the poli- mitment to high levels of collaboration. Oracle that have made so large a commitment tics behind release dates and couldn’t care less to language development: Apple, Google, and whether discussions are held in public or not; Andrew Binstock, Editor in Chief Microsoft. But none of them have adopted this they just want the new technology to be released [email protected] open, consensual approach. (I’m not here dep- and so are frustrated by the succession of delays. @platypusguy recating those companies’ work on their lan- This perspective is driving an initiative to 04

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //letters to the editor /

MAY/JUNE 2017 Exception Swallowing in Project Lombok low, wrap into RuntimeException, or otherwise modify In your excellent May/June 2017 issue, I want to com- any exceptions of the listed checked exception types. The magazine ment on your article “Project Lombok: Clean, Concise JVM does not check for the consistency of the checked By and for the Java community Code,” in which Josh Juneau presents a concise guide exception system; javac does, and this annotation lets you to using Lombok. On page 14, Juneau states, “The opt out of its mechanism.” @SneakyThrows annotation can be placed on a method Libraries to essentially ‘swallow’ the exceptions.” I think this Downloading Java Magazine 10 16 34 28 sentence is somewhat misleading. To me the term Two readers inquired why they could not see the LOMBOK: JDEFERRED’S DATABASE BEST PRACTICES ANNOTATIONS FOR ASYNC EVENT ACCESS WITH FOR LIBRARY CLEANER CODE MANAGEMENT STREAMS DESIGN swallow means to catch the exception, do nothing download icon for Java Magazine when they accessed ORACLE.COM/JAVAMAGAZINE with it, and continue execution of the code. the new page. Downloading the PDF version of the MAY/JUNE 2017 However, this is far from what Lombok is doing. magazine is a subscriber privilege. So you must log From the Lombok site, “Lombok will not ignore, wrap, in to access the PDF. As we have increasingly opened replace, or otherwise modify the thrown checked the magazine (making articles available without exception; it simply fakes out the compiler.” This login), you might be reading the issue without log- means we will still get an exception bubbling through ging in. To force a login, go to the quiz (which is also a should one occur, but we don’t need to explicitly han- subscriber-only benefit) and you’ll be asked to log in. dle it in calling code, much like runtime exceptions. When you do so from a laptop or desktop, you’ll see —Syed Asghar the download icon in the right margin.

Author Josh Juneau responds: “Thanks for sending me Contact Us this useful feedback. I am glad that you found the article We welcome comments, suggestions, grumbles, kudos, useful. I can certainly see why you find the termswal - article proposals, and chocolate chip cookies. All but low misleading with respect to the way in which the the last two might be edited for publication. If your @SneakyThrows annotation handles checked exceptions. note is private, indicate this in your message. Write to I do agree, after reassessing, that this was not an ideal us at [email protected]. For other ways to reach choice of words. The Lombok @SneakyThrows annotation us, see the last page of this issue. allows you to omit a try-catch clause and throw a checked exception—it does not silently swallow it. Perhaps the term hides would be more precise, as Lombok hides the requirement to code a try-catch clause by allowing you to throw a checked exception without it. As stated in the Lombok Javadoc, @SneakyThrows does not silently swal-

05

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //events /

JCrete sists of around 200 speakers and JULY 16–21 7 parallel tracks over 2 days, plus KOLYMBARI, GREEECE an additional day of workshops This loosely structured “uncon- beforehand. You will be joined by ference” involves morning ses- approximately 3,000 of your fel- sions discussing all things Java, low Java developers. Included in combined with afternoons spent the ticket price is a membership socializing, touring, and enjoy- in javaBin. ing the local scene. There is also a JCrete4Kids component for intro- Strange Loop ducing youngsters to program- SEPTEMBER 28–30 ming and Java. Attendees often ST. LOUIS, MISSOURI bring their families. Strange Loop is a multidisci- plinary conference that brings ÜberConf together the developers and JULY 18–21 thinkers building tomorrow’s DENVER, COLORADO technology in fields such as ÜberConf 2017 will be held at the emerging languages, alterna- Westin Westminster in down- tive databases, concurrency, town Denver. Topics include distributed systems, security, Java 8, microservice architectures, and the web. Talks are, in gen- JVM Language Summit Docker, cloud, security, Scala, eral, code-heavy, not process- JULY 31–AUGUST 2 Groovy, Spring, Android, iOS, oriented. A preconference day on SANTA CLARA, CALIFORNIA NoSQL, and much more. September 28 is optional and not The JVM Language Summit is an open technical collaboration among lan- included in the conference rate. guage designers, compiler writers, tool builders, runtime engineers, and JavaZone 2017 architects who target the JVM. The schedule consists of a single track of SEPTEMBER 12, WORKSHOPS NFJS Boston traditional presentations (about six each day) interspersed with workshop SEPTEMBER 13–14, CONFERENCE SEPTEMBER 29–OCTOBER 1 discussion groups. Each registrant is invited to suggest a few topics of OSLO, NORWAY BOSTON, MASSACHUSETTS interest for the workshops. JavaZone is a conference for Since 2001, the No Fluff Just Stuff Java developers created by the (NFJS) Software Symposium Tour Norwegian Java User Group, has delivered more than 450 javaBin. The conference has events with more than 70,000 existed since 2001 and now con- attendees. This event in Boston

PHOTOGRAPH BY BOB ADLER/THE VERBATIM AGENCY 06

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //events /

Oracle Code Events Oracle Code is a free event for developers to learn about the latest development technologies, practices, and trends, including containers, microservices and API applications, DevOps, databases, open source, development tools and low-code platforms, machine learning, AI, and chatbots. In addition, Oracle Code includes educational sessions for developing soft- ware in Java, Node.js, and other programming languages and frameworks using , MySQL, and NoSQL databases.

ASIA PACIFIC JULY 18, Sydney, Australia covers the latest trends within ing releases of Java SE, Java EE, AUGUST 10, Bangalore, India the Java and JVM ecosystem, and JavaFX; JVM languages; new AUGUST 30, Seoul, South Korea DevOps, and agile development development tools; insights into environments. recent trends in programming; and tutorials on numerous related JavaOne Java and JVM topics. in the fields of Java, micro­ O’Reilly Software Architecture OCTOBER 1–5 services, continuous delivery, Conference SAN FRANCISCO, CALIFORNIA JAX London and DevOps. Conference ses- OCTOBER 16–18, CONFERENCE Whether you are a seasoned OCTOBER 9–12 sions, keynotes, and expo happen AND TUTORIALS coder or a new Java programmer, LONDON, ENGLAND October 10–11. Hands-on work- OCTOBER 18–19, TRAINING JavaOne is the ultimate source of JAX London is a four-day confer- shops take place the day preced- LONDON, ENGLAND technical information and learn- ence for cutting-edge software ing and the day following the For four days, expert practitio- ing about Java. For five days, Java engineers and enterprise-level main conference. ners share new techniques and developers gather from around professionals, bringing together approaches, proven best prac- the world to talk about upcom- the world’s leading innova­tors tices, and exceptional technical

PHOTOGRAPH BY MASSMATT/FLICKR 07

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //events /

skills. At this conference, you’ll cutting-edge Java and web devel- hear about the best tools to use opment, software architecture, and why, and the effect they can and innovative infrastructures. have on your work. You’ll learn Experts share their professional strategies for meeting your com- experiences in sessions and work- pany’s business goals, developing shops. This year’s focus is on Java leadership skills, and making the core and enterprise technologies, conceptual jump from software the Spring ecosystem, JavaScript, developer to architect. continuous delivery, and DevOps.

KotlinConf QCon San Francisco NOVEMBER 2–3 NOVEMBER 13–15, CONFERENCE SAN FRANCISCO, CALIFORNIA NOVEMBER 16–17, WORKSHOPS October 1–5, 2017 KotlinConf is a JetBrains event SAN FRANCISCO, CALIFORNIA that provides two days of content Although the content has not San Francisco, California from Kotlin creators and commu- yet been announced, recent nity members. QCon conferences have offered #JavaOne several Java tracks along with Devoxx tracks related to web develop- NOVEMBER 6–10 ment, DevOps, cloud computing, ANTWERP, BELGIUM and more. The largest gathering of Java developers in Europe takes place Are you hosting an upcoming again this year in Antwerp. Java conference that you would Dozens of expert speakers deliver like to see included in this cal- hundreds of presentations on endar? Please send us a link Java and the JVM. Tracks include and a description of your event server-side Java, cloud, big data, at least 90 days in advance at and extensive coverage of Java 9. [email protected]. Other ways to reach us appear on the W-JAX last page of this issue. NOVEMBER 6–10 REGISTER NOW MUNICH, GERMANY W-JAX is a conference dedicated to 08

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 Your Destination for Oracle and Java Expertise

Written by leading Java experts, Oracle Press books offer the most definitive, complete, and up-to-date coverage of Java available.

Java: A Beginner’s Guide, Java: The Complete OCA Java SE 8 Rapid Modernization 7th Edition Reference, Programmer I Exam Guide of Java Herb Schildt 10th Edition (Exam 1Z0-808) Applications Revised to cover Java SE 9, Herb Schildt Kathy Sierra, Bert Bates G. Venkat this book gets you started Updated for Java SE 9, this book Get complete coverage of all Adopt a high-performance programming in Java right away. shows how to develop, compile, objectives for Exam 1Z0-808. enterprise Java application debug, and run Java programs. Electronic practice exam modernization strategy. questions are included.

Available in print and eBook formats. www.OraclePressBooks.com • @OraclePress JAVA 9 Inside JDK 9

JAVA 9 FEATURES 11 | FROM JAVA 8 TO JAVA 9 17 | COLLECTIONS AND STREAMS 21 | JSHELL 28 | HTTP/2 39

his single-topic issue of Java Magazine focuses on the benefits article (page 11) provides an overview of many of these useful additions. of the new JDK 9 release other than the Java Platform Module His work is complemented by an in-depth examination (page 21) of the System (JPMS). The modularity feature, often touted as the new features in Collections, Streams, and iterators. Also, Trisha Gee central part of this release, was not yet in final approved form explains (page 17) how to compile and run Java 8 code on Java 9, even if when we went to press. So, rather than provide early informa- you’re not using modules. Ttion that might be wrong later, we’ve chosen to focus on the other parts An alternative way to run Java 9 code is with JShell, which is a new of JDK 9, which have been formal- read-evaluate-print loop (REPL) ized and finished and will ship bundled with this release. Our whenever modules are officially introduction to JShell (page 28) approved. At present, that ship- shows the basics, while our article ping date is expected to be in late on HTTP/2 (page 39) provides addi- September. The reasons for this tional examples of JShell usage. delay are discussed in the edito- The HTTP/2 technology, which rial (page 3). Shortly after that facilitates network programming, date, Java Magazine will dedicate a is part of a new incubator system second issue to Java 9, with a deep introduced in Java 9 that presents focus on the new modular archi- developers with technologies that tecture and how best to use it. are likely to be bundled in future As the articles in this issue releases. If you regularly use HTTP, demonstrate, there is a lot of take a long look at this article. goodness in Java 9 outside of mod- In addition to these articles, we ules. The language and platform also have our usual language quiz, teams have created dozens of con- events calendar, and letters to the venient new features that make editor. Enjoy, and let us know if Java programming more succinct there are other Java 9 topics you’d and enjoyable. Simon Ritter’s like us to cover in the future.

ART BY I-HUA CHEN 10

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //java 9 / Nine New Developer Features in JDK 9 There’s a lot more to this release than modules. SIMON RITTER

he big new feature in JDK 9 is the Java Platform Module myList.add(new Point(4, 4)); TSystem coupled with the introduction of the modular JDK. myList = Collections.unmodifiableList(myList); However, there are plenty of other new features in JDK 9, and in this article, I focus on nine that are of particular interest It’s not terrible, admittedly, but to create an immutable list to developers. Where applicable, I’ve included the relevant of four Points required six lines of code. JDK 9 addresses this JDK Enhancement Proposal (JEP) number so you can find through factory methods for collections. more information. This feature makes use of a change introduced in JDK 8 that enabled static methods to be included in interfaces. That Factory Methods for Collections (JEP 269) change means that you can add the necessary methods at Collections provide a well understood way for you to gather the top-level interfaces (Set, List, and Map) rather than hav- together groups (I was going to say sets, but that could be a ing to add them to a large group of classes that implement bit misleading) of data items in your applications and then those interfaces. manipulate the data in a variety of useful ways. Let’s rewrite our example using JDK 9: At the top level, there are interfaces that represent the abstract concepts of a List, Set, and Map. List list = The problem, until now, has been that Java doesn’t pro- List.of(new Point(1, 1), new Point(2, 2), vide a simple way to create a collection with predefined data. new Point(3, 3), new Point(4, 4)); If you want a collection to be structurally immutable (that is, you can’t add, delete, or change references to elements), you The code is now much simpler. need to do more work. The rules that apply to the use of the different collections Let’s look at a simple example using JDK 8: also apply (as you would expect) when using these factory methods. So, you cannot pass duplicate arguments when you List myList = new ArrayList<>(); create a Set, nor can you pass duplicate keys when you create myList.add(new Point(1, 1)); a Map. A null value cannot be used as a value for any collec- myList.add(new Point(2, 2)); tion factory method. The Javadoc documentation provides full PHOTOGRAPH BY BOB ADLER/ THE VERBATIM AGENCY myList.add(new Point(3, 3)); descriptions of how the methods may be called. [Collections 11

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //java 9 /

are discussed further in the article “Java 9 Core Library dropWhile() method does the Updates: Collections and Streams” (page 21). —Ed.] opposite; it drops elements from JDK 9 includes a the input stream until the test() new read-eval- Optional Class Enhancements method of the Predicate returns print loop (REPL) The Optional class was introduced in JDK 8 to reduce the true. All remaining elements of number of places where a NullPointerException could be the input stream are then passed command-line tool, generated by code (and it was frequently used to make the to the output stream. jshell, that allows you to Stream API more robust). Be careful when using either develop and test Java JDK 9 adds four new methods to Optional: of these methods when you have ■■ ifPresent(Consumer action): If there is a value present, an unordered stream. Because code interactively. perform the action using the value. the predicate needs to be sat- ■■ ifPresentOrElse(Consumer action, Runnable emptyAction): isfied only once to change the Similar to ifPresent, but if there is no value, it executes the state of elements being passed emptyAction. to the output, you might get elements in the stream that ■■ or(Supplier supplier): This method is useful when you you don’t expect, or you might miss ones you thought you want to ensure that you always have an Optional. The would get. or() method returns the same Optional if a value is The third new method is ofNullable(T t), which returns present; otherwise, it returns a new Optional created by a stream of zero or one elements, depending on whether the the supplier. value passed is null. This can be very useful to eliminate a ■■ stream(): Returns a stream of zero or one elements, null check before constructing a stream, and it is similar in a depending on whether there is a value. sense to the new stream() method in the Optional class dis- cussed in the previous section. Stream API Enhancements The last new stream method is a new version of the It’s always useful to be able to create a stream source from a static iterate() method. The version in JDK 8 took one collection of data, and JDK 8 provided several methods to do parameter as the seed and created an infinite stream as this outside the Collections API (BufferedReader.lines(), for output. JDK 9 adds an overloaded method that takes three example). Several new sources are being added in JDK 9, such parameters, which effectively gives you the ability to repli- as java.util.Scanner and java.util.regex.Matcher. cate the standard for loop syntax as a stream. For example, JDK 9 adds four methods to the Stream interface. Stream.iterate(0, i -> i < 5, i -> i + 1) gives you a First, there are two related methods: takeWhile(Pred­ stream of integers from 0 to 4. icate) and dropWhile(Predicate). These methods are complementary to the existing limit() and skip() meth- Read-Eval-Print Loop: jshell (JEP 222) ods, but they use a Predicate rather than a fixed integer JDK 9 includes a new read-eval-print loop (REPL) command- value. The takeWhile() method continues to take elements line tool, jshell, that allows you to develop and test Java code from the input stream and pass them to the output stream interactively, unlike when you use an IDE, where code must until the test() method of the Predicate returns true. The be edited, compiled, and then run. Developers can quickly 12

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //java 9 /

prototype sections of code as jshell Reactive streams use a publish-subscribe model in which continually reads user input, eval- The introduction the stream processor (the subscriber) subscribes to the sup- uates it, and prints either the value of private methods plier of elements (the publisher). By doing this, the supplier of the input or a description of the in interfaces will knows how many elements it can pass to the processor at any state change the input caused. time. If the supplier needs to send more than this number, To make the tool easier to allow common code it can use techniques such as local buffering or it can use an use, it includes features such as to be extracted to alternative processor (this is a typical microservice approach an editable history, tab comple- methods that will that delivers horizontal scalability by spinning up new ser- tion, automatic addition of termi- vice instances to handle increased load). nal semicolons when needed, and remain encapsulated JDK 9 includes a new class, Flow, that encloses several configurable predefined imports within the interface. interfaces: Flow.Processor, Flow.Subscriber, Flow and definitions. It is also possible .Publisher, and Flow.Subscription. A Subscription is to declare variables whose type is used to link a Publisher with a Subscriber. defined after the declaration (but The Subscription interface contains two methods: this is still not dynamic typing: once the type is set, it can’t ■■ cancel(): This method causes the Subscriber to stop be changed). receiving messages (eventually). There is even a module, jdk.jshell, that can be used if ■■ request(long n): Add n elements to the number that the you want to build your own “snippet” evaluation tool. Subscriber is able to process. This method can be called One of the most significant reasons for including a REPL repeatedly as the Subscriber processes elements and is in the JDK is to make it easier to use Java as a teaching lan- ready to process more. guage, lowering the amount of boilerplate code new develop- By implementing the Processor interface, a class can act as ers need to write before they get results. both a publisher and a subscriber, thereby acting as an inter- mediate operation in the stream. Concurrency Updates (JEP 266) The second new concurrency feature in JDK 9 consists Java 5 introduced concurrency utilities to simplify writing of enhancements to the CompletableFuture class, which was Java code that has multiple cooperating threads. Subsequent introduced in JDK 8. Several new methods relate to adding releases have improved these features by adding things such time-based functionality. These enhancements enable the as the fork/join framework in JDK 7 and, most recently, paral- use of time-outs via methods such as completeOnTimeout(), lel streams in JDK 8. Now, JDK 9 provides enhancements for delayedExecutor(), and orTimeout(). Other new methods concurrency in two areas. include failedFuture() and newIncompleteFuture(). The first is a reactive streams publish-subscribe frame- work. Processing streams of elements in an asynchronous Milling Project Coin (JEP 213) fashion can lead to problems when the rate at which elements One of the most significant changes in JDK 7 was Project are submitted to the processing code rises sharply. If the pro- Coin, which was a set of small language changes to smooth cessor is unable to handle the load, the element supplier can out some of the common tasks developers undertake repeat- be blocked or a buffer overflow situation can occur. edly in Java. The project included things such as the ability to 13

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //java 9 /

use Strings as constants in switch statements. JDK 9 builds on result in a type being inferred this and adds a few more small changes to the language syn- that is not denotable. A type The ProcessHandle tax of Java: that is not denotable can be interface identifies ■■ Effectively final variables can be used in try-with-resources represented by the compiler, and provides control of without being reassigned. Currently, each resource that but it cannot be expressed to is used must be assigned to a new variable, even if that the JVM using the class signa- native processes. resource has already been defined in the method. With this ture attribute. In JDK 9, it is now change, it is now possible to use an existing variable (as possible to use the diamond long as it is effectively final) without reassigning it. Here is operator with an anonymous an example of the change: class as long as the inferred type is denotable, for example:

try (Resource r = alreadyDefinedResource) ... List myList = new ArrayList<>() { // Overridden methods In JDK 9, it becomes this: };

try (alreadyDefinedResource) ... ■■ A single underscore will no longer be valid as an identifier. I often ask, during Java 9 presentations, if anyone has ever ■■ Private methods can be used in interfaces. Interfaces used a single underscore as a variable name and, thank- changed in a big way in JDK 8. First, there was the introduc- fully, few people have. The reason for doing this is that in a tion of default methods, which allowed new methods to be later release of the JDK (presumably JDK 10), it will be valid added to existing interfaces without forcing a break in back- to use a single underscore as a variable name only in lambda ward compatibility. Because this meant that behavior could expressions. This makes sense. You could use a single be included in an interface (giving Java multiple-inheritance underscore if your lambda expression takes only one argu- of behavior for the first time), it was also logical to include ment and you don’t use the argument in the body of the static methods. In JDK 9, the introduction of private meth- lambda, for example: ods in interfaces will allow common code to be extracted to methods that will remain encapsulated within the interface. _ -> getX() ■■ The diamond operator can be used with anonymous classes. One of the things included in JDK 8 and now JDK 9 is better (For those of you who like the idea of underscores as vari- type inference. Being able to use lambda expressions with- able names, you can still use two or more as an identifier.) out explicitly specifying the types of parameters is a good ■■ Extended use of the @SafeVarargs annotation is allowed. example of this. This ability required a substantial rewrite Currently, this annotation can be used only on constructors, of how the Java compiler processes type inference, and the static methods, and final methods, none of which can be diamond operator change in JDK 9 makes use of that com- overridden. Because a private method cannot be overridden piler change. The problem, as it existed before, was that by a subclass, it is logical also to enable private methods to using the diamond operator with an anonymous class could use this annotation. 14

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //java 9 /

Spin-Wait Hints (JEP 285) compare-and-set operations, but without the performance This is a small change because it adds only a single method, overhead that is associated with using the equivalent classes but its addition to the class is significant. The other and methods of the java.util.concurrent.atomic package. interesting aspect of this feature is that it is the first JEP to be You can also use a VarHandle to “fence” operations, giv- included that was proposed by a company other than Oracle ing you fine-grained control over the ordering of (in this case, Azul Systems). operations such as read and write or store and load. This can The onSpinWait() method provides a hint to the JVM that be useful in situations where you don’t want the Java compiler the thread is currently in a processor spin loop. If the JVM and or JVM to reorder operations, which is often done to optimize hardware platform support optimizations when spinning, the performance of code paths. such hints can be used; otherwise, the call is ignored. Typical optimizations include reducing thread-to-thread latencies Process API Updates (JEP 102) and reducing power consumption. JDK 9 contains enhancements to the Process and ProcessBuilder classes and introduces a new ProcessHandle Variable Handles (JEP 193) interface. ProcessBuilder now includes the method One of the most significant changes in JDK 9 caused by mod- startAsPipeline(). As the name suggests, this method ularizing the core JDK libraries is the encapsulation of the constructs a UNIX-style pipeline of processes using a list of internal APIs by default. Probably the most well known of ProcessBuilders. As each process is started, its standard out- these is sun.misc.Unsafe. To make some of the functionality put is connected to the standard input of the next process. of this private API available through a public API, JDK 9 intro- Here’s a simple example that pipes the output of the duces the VarHandle class. UNIX/Linux ls command on /tmp through wc –l to get a Variables are used in Java all the time. They are implicit count of the number of files in the tmp directory: pointers to areas of memory that hold values. A variable han- dle is a typed reference to a variable (so for those who’ve used ProcessBuilder ls = new ProcessBuilder() C and C++, it’s effectively a pointer to a pointer). .command("ls") In order to get a reference to a VarHandle, you use the .directory(Paths.get("/tmp").toFile()); MethodHandle.Lookup class that has been extended in JDK 9. ProcessBuilder wc = new ProcessBuilder() You can retrieve references to .command("wc", "-l") either static or nonstatic vari- .redirectOutput(Redirect.INHERIT); ables, as required, as well as With features such List lsPipeWc = ProcessBuilder to arrays. as these, you should .startPipeline(asList(ls, wc)); Once you have a VarHandle, you can execute low-level consider migrating The ProcessHandle interface identifies and provides control of memory ordering operations on your development to native processes. It provides methods to retrieve information the variable it references. This this release ASAP. about a process, such as the process ID as well as any child capabil ­ity allows you to per- and descendant processes. Also, there is a static method that form atomic operations, such as returns an Optional for a given process ID. 15

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////// JULY/AUGUST 2017 //java 9 / //java proposals of interest /

The subinterface ProcessHandle.Info provides a range of process-specific details, such as the command line used to start the process, when the process started, and the identity FEATURED JDK ENHANCEMENT PROPOSAL of the user that started the process. The Process class has seven new methods that pro- JEP 241: Veteran Tool jhat vide access to more information about the native process. Some of these overlap with those available through the Reaches Retirement ProcessHandle: ■■ children() and descendants(): Lists the process’s children The release of JDK 9 contains lots of goodies, as this or dependents, respectively issue of Java Magazine has reported in detail. However, ■■ getPid(): Returns the ID of the given process due to the approval of JDK Enhancement Proposal 241 ■■ info(): Returns a snapshot of information as a Process (JEP 241), the jhat heap analysis tool will no longer be Handle.Info instance bundled. jhat originally made its way into the JDK with ■■ onExit(): Is a CompletableFuture that can be used to per- the release of Java 6. It came from a project called HAT form tasks when the process terminates and was a part of the now defunct javatools projects ■■ supportsNormalTermination(): Determines whether before its incorporation into the JDK. destroy() terminates the process normally Despite its inclusion in recent releases of the JDK, ■■ toHandle(): Returns the ProcessHandle of this process it was always categorized as an experimental tool and labeled as such in all official documentation. Over the Conclusion years, other heap profilers have surpassed it, and so jhat As you can see, there are many useful and powerful new has been in an extended decline with little maintenance features included in JDK 9 that are particularly targeted at being accorded to it. developers. With features such as these, you might want to If you’re still using jhat, you should consider other consider migrating your development to this release as soon tools. Two worthy options are VisualVM and, at a pro- as you can.