List groceryTransactions = List transactionsIds = //MAY/JUNE 2015 / new Arraylist<>(); transactions.stream() .filter(t -> t.getType() == Transaction.GROCERY) for( Transaction t: transactions ){ .sorted(comparing(Transaction::getValue).reversed()) if( t.getType() == Transaction.GROCERY ){ .map(Transaction::getId) groceryTransactions.add(t); .collect(toList()); } } // as a parallel stream:

Collections.sort(groceryTransactions, new Comparator(){ List transactionsIds = public int compare(Transaction t1, Transaction t2){ transactions.parallelStream() return t2.getValue().compareTo(t1.getValue()); .filter(t -> t.getType() == Transaction.GROCERY) } .sorted(comparing(Transaction::getValue).reversed()) }); .map(Transaction::getId) .collect(toList()); List transactionIds = new ArrayList<>(); for( Transaction t: groceryTransactions ){ List transactionsIds = transactionsIds.add(t.getId()); transactions.stream() } .filter(t -> t.getType() == Transaction.GROCERY) .sorted(comparing(Transaction::getValue).reversed()) List groceryTransactions = .map(Transaction::getId) new Arraylist<>(); .collect(toList()); for( Transaction t: transactions ){ // as a parallel stream: if( t.getType() == Transaction.GROCERY ){ groceryTransactions.add(t); List transactionsIds = { transactions.parallelStream() } Twenty years of } .filter(t -> t.getType() == Transaction.GROCERY) .sorted(comparing(Transaction::getValue).reversed())language evolution Collections.sort(groceryTransactions, new Comparator(){ .map(Transaction::getId) public int compare(Transaction t1, Transaction t2){ .collect(toList()); and JVM innovation return t2.getValue().compareTo(t1.getValue());GROWS UPList transactionsIds} = } transactions.stream() }); INTERVIEWS WITH IOT: MAKING .fiWHAT’Slter(t -> NEW t.getType() ==ROBOTS: Transaction.GROCERY) JAVA 13 MARK REINHOLD 31 COFFEE WITH JAVA 24.sorted(comparing(Transaction::getValue).reversed())IN JPA? 62 INSIDE THE ListAND transactionIds JOHN ROSE = new ArrayList<>(); .map(Transaction::getId) MACHINE for( Transaction t: groceryTransactions ){ .collect(toList()); ORACLE.COM/JAVAMAGAZINE //table of contents / COMMUNITY 13 15 20 A CONVERSATION A CONVERSATION WITH JOHN ROSE WITH MARK THE MASTERS With Projects Valhalla REINHOLD and Panama, the JVM The changes that have continues to add useful driven Java’s wide use, JAVA IN ACTION SPEAK features. and the changes to come JAVA TECH

COMMUNITY 31 48 62 03 Internet of Things Career Architect From the Editor Brewing Java with the More Ideas to Boost Robots Running Wild Warning: Java Magazine is going radically Raspberry Pi Your Developer Career Using the Java NAOqi SDK to more technical. Interact with a USB scale to accurately Study code, go to conferences, but use program companion robots

06 measure your coffee beans and brew the conferences to build your network. 68 ABOUT US Java Nation the perfect cup of Java. 52 Contact Us Calendar of events, the NYJavaSIG, the 38 JCP Executive Series Have a comment? Suggestion? Units of Measurement API, interview Architect Working on Java from Want to submit an article proposal? with Java Champion Arun Gupta Contexts and Dependency Within the JCP Here’s how to do it. 11 Injection: the New Java EE SourcePoint’s Geir Magnusson Jr. Java Books Toolbox discusses the advantages of building Review of Core Java for the Impatient Using strong typing in dependency systems with Java, and how the JCP and news blurbs of other worthy reads injection in Java EE has affected the platform’s evolution. 44 JAVA IN ACTION JAVA TECH New to Java 24 57 Create a Simple Paddle Game blog What’s New in JPA with Microsoft Kinect Deep Learning Attribute conversion, schema Startup Skymind looks to take deep More fun with using Greenfoot learning technology out of the labs and generation, enhanced SQL queries, to drive Kinect from Java and a host of other improvements into the enterprise with an open source highlight JPA 2.1. framework built on Java and Hadoop. 01

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 EDITORIAL PUBLISHING Editor in Chief Publisher Andrew Binstock Jennifer Hamilton +1.650.506.3794 COMMUNITY Interim Associate Editor Associate Publisher and Audience Kay Keppler Development Director Copy Editors Karin Kinnear +1.650.506.1985 20 Years of Claire Breen, Karen Perkins Audience Development Manager Section Development Jennifer Kurtz Blair Campbell - Java in Action Michelle Kovac - Java in Action, Features ADVERTISING SALES Bob Larsen - Java Nation President, Sprocket Media Yolande Poirier - Java Nation Kyle Walkenhorst +1.323.340.8585 Innovation Technical Reviewers Western and Central US, LAD, and Canada, Sprocket Media

Stephen Chin, Reza Rahman, Simon Ritter, IN ACTION JAVA # James Weaver Tom Cometa +1.510.339.2403 1 Development Platform Eastern US and EMEA/APAC, DESIGN Sprocket Media Senior Creative Director Mark Makinney +1.805.709.4745 Francisco G Delgadillo Advertising Sales Assistant Design Director Cindy Elhaj +1.626.396.9400 x 201 Richard Merchán Mailing-List Rentals Contributing Designers Contact your sales representative. Jaime Ferrand, Diane Murray, Arianna Pucherelli RESOURCES TECH JAVA Production Designers Oracle Products Sheila Brennan, Kathy Cygnarowicz +1.800.367.8674 (US/Canada) Oracle Services Since 2002 Since 1999 Since 1995 +1.888.283.0591 (US) Oracle Press Books oraclepressbooks.com

ARTICLE SUBMISSION Since 1996 Since 1998 Since 1996 ABOUT US If you are interested in submitting an article, please e-mail the editors. SUBSCRIPTION INFORMATION Subscriptions are complimentary for qualified individuals who complete the subscription form. MAGAZINE CUSTOMER SERVICE Since 1996 Since 2008 Since 1998 [email protected] Phone +1.847.763.9635 PRIVACY Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer that your mailing address or e-mail address not be included in this program, contact Customer Service. Since 1999 Since 2001 Since 1996 Since 2012

Copyright © 2015, 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 DAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN. 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 blog 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 Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Java Magazine is published bimonthly at no cost to qualified subscribers by Oracle, 500 Oracle Parkway, MS OPL-3A, Redwood City, CA 94065-1600. Digital Publishing by GTxcel 02

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //from the editor / COMMUNITY JAVA IN ACTION BIO Warning: We’re Going Technical Java Magazine heads in a new direction. JAVA TECH everal weeks ago, I was hired by Oracle to ers who work regularly with code. The magazine will head up Java Magazine. This happy event both reflect and cater to our shared love of pro- S means that I get to write about Java from the gramming, our passion for great tools and technolo- very heart of Java. How cool is that? The joy I feel is gies, and the abiding enjoyment we all derive from akin to the excitement of setting out on a journey Java and JVM languages. for which one has long prepared. I’ve been an edi- To do this, we’ll enlist more Java experts, accom- ABOUT US tor of developer publications for many years, most plished programmers, algorithm junkies, design recently heading up Dr. Dobb’s. I’ve also spent much mavens, build wizards, bad-code scolds, experi- of my free time during the last 10 years program- enced teachers, and skilled architects to share their ming in Java and, to a lesser extent, Groovy. wisdom in our pages. We’ll also explore tools— Mixed with the joy of this new work is the aware- especially open source tools—and important open ness of the long road ahead, defined by the end- source projects. point I am driving toward; so, let me share my plans I also expect to remove some sections, mainly for the new direction of our magazine. those that don’t focus tightly on program- In simple terms, I plan to take Java Magazine in ming. There will be fewer case histories in Java blog a radically more technical direction. The editorial Magazine—and those that do appear will bear team and I will be catering squarely to Java develop- directly on a relevant technical topic. We’ll also

PHOTOGRAPH BY BOB ADLER/GETTY IMAGES 03

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //from the editor /

transform other sections. For exam- readers), and to Kay Keppler, who ple, the section that used to con- was the key to making this transi- COMMUNITY tain book blurbs will run detailed tion possible. Learn Java 8 reviews, signed by the reviewers. Finally, allow me to emphasize (The first book review appears on one more point: I really like hear- page 11 of this issue.) ing from you. Comments, plaudits, From the Source Finally, you’ll see fewer articles grumbles, contrasting opinions, telling you how great Java is. There’s corrections, proposals for articles— JAVA IN ACTION no need for that. You get it. I get it. these are all welcome and make for Oracle University Let’s move forward. a better magazine. My address is You can expect to see these at the end of this editor’s note, and changes roll out over the next few more contact information appears

issues. Changing magazines is not on the Contact Us page at the end JAVA TECH New Java SE 8 training and certification a stop-the-world-while-I-do-this of the magazine. Our staff reminds kind of project. It’s more like chang- me that the last paragraph of that Available online or in the classroom ing a tire on a moving truck. In this page should not be overlooked. issue, you’ll see some initial tweaks. Looking forward to this journey Taught by Oracle experts For example, code is now presented together,

100% student satisfaction program ABOUT US in a monospaced font (hey, hey!). There’s also a new last page about Andrew Binstock, Editor in Chief how to contact us and propose [email protected] articles. The next issue will have @platypusguy more-substantial changes, and the one after that will have a lot more PS: For more on my background, of the content I have promised. By you can click on the link marked year’s end, the transition will be “Bio” on the previous page. Learn More nearly complete and we should be rolling in high gear. blog A word of thanks to my predeces- sor, Caroline Kvitka, for bringing Java Magazine to this point (where we have nearly a quarter of a million 04

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015

//java nation /

Devoxx UK COMMUNITY São Paulo, Brazil JUNE 17–19 LONDON, ENGLAND The innovative London Java User Group organizes this conference, and puts developers front and center with the theme “The League

of Extraordinary Developers.” IN ACTION JAVA The schedule is packed with pre- sentations, hands-on-labs, and Birds-of-a-Feather (BOF) sessions. Developers can meet top British and international experts in a

casual atmosphere. TECH JAVA

Devoxx Poland JUNE 22–25 KRAKOW, POLAND Seven tracks focus on Java tech- nology. Participants can dive deep

in the conference sessions, ABOUT US evening BOFs, and workshops and labs led by world-class trainers. QCon New York EVENTS JUNE 8–12 Java EE Summit NEW YORK, NEW YORK JUNE 24–26 JavaOne Latin America JUNE 23–25 QCon is designed for technical MUNICH, GERMANY SÃO PAULO, BRAZIL team leads, architects, engineer- The Java EE Summit includes 14 JavaOne Latin America is the premier Java conference in Latin ing directors, and project manag- intensive workshops led by top America. Visionaries and world-renowned speakers will present con- ers who influence innovation. The German-speaking Java EE experts. ference and hands-on sessions in five tracks, including clients and event includes two days of tutori- Developers and software architects blog the user interface; core Java platform; Java and the Internet of Things; als followed by a three-day confer- will receive in-depth knowledge server-side Java; and a new track about Java, DevOps, and the cloud. ence. One track focuses on Java to plan and implement successful innovations. Java EE 6 and Java EE 7 projects.

PHOTOGRAPH BY GETTY IMAGES 06

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java nation /

EVENTS OSCON Fix This—Solution COMMUNITY JULY 20–24 PORTLAND, OREGON In the March/April 2015 issue’s Fix This, Stephen Chin FISL Open source pioneers, experts, and inno- showed us a problem of the new TemporalAdjuster JULY 8–11 vators have gathered at OSCON over the class introduced with the Java SE 8 Date and Time API: PORTO ALEGRE, BRAZIL past decade. With a dozen tracks and What if you want to do something specific to your appli- The International Free Software Forum hundreds of sessions, the conference has cation, such as finding the next occurrence of Friday the

(FISL) event is jam-packed with lec- practical tutorials, inspirational keynotes, 13th? Here’s a quick explanation of each possible issue: IN ACTION JAVA tures, workshops, demonstrations, and a wealth of information on open and presentations. source languages and platforms. 1). Variations in month. By using thetemporal.plus method, variances in month length are automatically fixed ÜberConf by the underlying LocalDate instance. JULY 21–24 2). A time zone issue. The underlying implementation

DENVER, COLORADO of a Temporal passed in to the TemporalAdjuster is TECH JAVA ÜberConf is part of the No Fluff Just Stuff responsible for taking care of compensating for time zones Software Symposium Series that explores (which would be the case if a ZonedDateTime was used, the ever-evolving ecosystem of the Java for example). platform. The conference offers 100 tech- 3) .An error in the formula. This is the problem. The for- nically focused sessions including more mula works fine if the given day of the month is on or than 25 hands-on workshops about archi- before the 13th or the given month has no Friday the 13th. tecture, cloud, security, enterprise Java, If both of those cases coincide, then the Temporal ABOUT US languages on the JVM, build/test, mobil- Adjuster incorrectly returns a date in the past. To fix this, ity, microservices, Docker, and agility. you can simply add a check for the day of the month and increment the month in advance of running the loop. Java Forum The Developer’s Conference (TDC) JULY 9 JULY 21–25 if (temporal.get( STUTTGART, GERMANY SÃO PAULO, BRAZIL ChronoField.DAY_OF_MONTH) > 13) Organized by the Stuttgart Java User One of Brazil’s largest conferences for temporal = Group, Java Forum attracts more than developers, IT professionals, and stu- temporal.plus(1, ChronoUnit.MONTHS); 1,000 participants who learn about Java dents offers Java tracks over five days. and the Java environment. The forum Java-focused content includes intro- A simple fix, and thanks to the new Date and Time API includes lectures, presentations, work- ductory sessions in the Java University you can focus on debugging your algorithm rather than blog shops, demos, and BOF sessions. track, and advanced and intermedi- second-guessing whether your date fields are 0, 1, or 1900 ate sessions in the Java EE, mobile, and based. (For an explanation, check out slide 10 of Chin’s embedded tracks. ZombieTime talk.)

PHOTOGRAPH BY GETTY IMAGES 07

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java nation /

FEATURED JAVA SPECIAL COMMUNITY

FEATURED JAVA SPECIFICATION REQUEST INTEREST GROUP: NEW YORK Long ago, on September 21, 1995— JSR 363: Units of back when the years still began with a 1 and flannel was considered the epit- IN ACTION JAVA Measurement API ome of fashion—a group of Java devel- opers gathered after a Java developer JSR 363: Units of Measurement API seeks conference. Because the term Java to support “the programmatic handling of user group didn’t exist yet, they called physical quantities and their expression as themselves the New York Java Special numbers of units.” It provides type-safe Interest Group (NYJavaSIG). TECH JAVA support for units of measure that is neces- Since that time, membership in the sary for machine-to-machine communica- NYJavaSIG has grown to almost 8,000 tion and the Internet of Things, especially of what Frank Greco, NYJavaSIG founder and leader as well as lead guitar- when you’re working with sensors or in ist for the NullPointers (the now world-famous band composed entirely of the manufacturing, engineering, or scien- Java developers), describes as “extremely opinionated technologists.” He tific fields. You have no need to worry if the quickly follows up with “But hey...it’s New York.” Monthly meetings aver- length passed to or from that API is in feet or age about 240 members, and bimonthly hands-on workgroups with titles ABOUT US meters—or even leagues! such as “Cloud/HPC and Languages” ensure that something will pique The Specification Leads for JSR 363—Jean- the interest of almost any Java developer. Marie Dautelle, Werner Keil, and Leonardo The future of NYJavaSIG looks to be every bit as promising as its past. Lima—are working with the support of gov- According to Greco, “The local NY Java community is enjoying a renais- ernment organizations, private companies, sance thanks to the release of Java 8 with new functionality and power. Java user groups, and individuals like you. If Every meeting seems to add many new NYJavaSIG members. And it you’d like to comment on or contribute to appears to be a larger phenomenon with Java excitement growing glob- the work on JSR 363, or even just track the ally. With more cloud and IoT [Internet of Things] functionality coming progress, visit java.net and help steer the and with the Java ecosystem growing even bigger, there’s still a lot of future of Java. excitement yet to come.” If you plan to be in the New York area and would like to participate in blog an NYJavaSIG event, look them up at the NYJavaSIG website or on Twitter @nyjavasig.

08

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java nation / COMMUNITY JAVA CHAMPION PROFILE ARUN GUPTA

Java Magazine: Where did Gupta: My first job was way Gupta: Meeting people of you grow up? back in 1996 doing Java different cultures from all Gupta: Delhi, India programming. around the world. I’ve been IN ACTION JAVA to more than 40 countries Java Magazine: When and Java Magazine: What do so far. how did you first become you enjoy for fun and interested in computers relaxation? Java Magazine: Has being and programming? Gupta: I like doing long- a Java Champion changed Gupta: My elder sister was distance running, teaching anything in your daily life? TECH JAVA doing a Master of Science STEM [science, technology, Gupta: Bragging rights. I degree in computers engineering, and math- also feel a social respon- when I was growing up, ematics] workshops to kids, sibility to grow the Java and I found that intrigu- and cooking with family. Champion circle bigger and ing and engaging. My first create more of us. interaction with comput- Java Magazine: What hap- ABOUT US ers was when I got a mas- pens on your typical day off Java Magazine: What are ter’s degree in computing from work? Do you spend you looking forward to in myself. time with family and/or the coming years? friends? Do you wander off Gupta: I want 9 million Java Java Magazine: What was alone? developers to grow to 10, 11, your first computer and Gupta: A day off is typically 12, and 13 million, and keep programming language? packed with kids’ activities, growing. Arun Gupta, the director of technologies since his days Gupta: Intel 386, 4 MB watching a movie with the technical marketing and as a founding member of RAM, 200 MB disk. First family, Devoxx4Kids work- Follow Arun Gupta’s blog developer advocacy at Red the Java EE team at Sun programming language: shops, and socializing with or reach him on Twitter Hat, promotes Red Hat Microsystems. He travels Pascal. friends. @arungupta. technologies that focus on the world speaking about a blog JBoss middleware. He has wide variety of topics and Java Magazine: What was Java Magazine: What “side been an avid proponent of is a JavaOne Rock Star and your first professional pro- effects” of your career do the Java community and best-selling author. gramming job? you enjoy the most? 09

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015

// java books / COMMUNITY

CORE JAVA FOR THE IMPATIENT By Cay S. Horstmann Addison-Wesley Professional, February 2015

This book follows on the slimmer volume Once into the meat of Java SE 8, however, JAVA IN ACTION JAVA by Horstmann, Java SE 8 for the Really Horstmann displays his widely recognized Impatient, which came out in early 2014. skill at explaining difficult concepts clearly That book targeted existing Java develop- and choosing code examples that cogently ers and explained concisely what was new support his textual presentation. The book in Java SE 8 (as well as some important but also contains many wise and pragmatic overlooked features in Java SE 7). recommendations about the right way to JAVA TECH JAVA This 500-page volume is an introduc- do things (a central strength of his previous tion to the full Java SE 8 language, aimed writings), so that the work is not merely an at developers coming to Java from another exposition but truly a guide. language, but not at novices new to pro- There is a fair amount of duplication gramming. It is a bridge between the between the examples in this book and earlier Java SE 8 book and the upcoming Horstmann’s earlier one on Java SE 8, so

revision of Core Java—the two-volume if you bought that book, I’d recommend ABOUT US masterpiece that Horstmann coauthors waiting for the arrival ofCore Java before with Gary Cornell—which should see light upgrading. However, for all other readers, later this year. this is an excellent tutorial for Java SE 8. To my eyes, the added introduction to the —Andrew Binstock language seems rushed and a bit too thin. For example, Horstmann writes, “Java has … five integral types.” Six pages later, he Over the next few issues, the book sec- asserts that “four [primitive types] are inte- tion of Java Magazine will evolve from ger types.” Only careful comparison reveals descriptive blurbs to critical reviews, that the char type has been reclassified signed by the respective authors. Due from its correct group (integral primitives) to potential conflicts of interest, books to an invented one (integer primitives) from Oracle Press will be presented but blog without explanation. It’s not a big point, not reviewed. —Ed. but it suggests that a reader looking to learn Java would find the early sections confus- ing, whereas they should be the simplest. 11

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java books / COMMUNITY JAVA IN ACTION JAVA

THE CUCUMBER FOR JAVA BOOK: NETBEANS IDE 8 COOKBOOK JAVA EE 7: THE BIG PICTURE BEHAVIOUR-DRIVEN DEVELOPMENT FOR By David Salter and Rhawi Dantas By Danny Coward JAVA TECH JAVA TESTERS AND DEVELOPERS Packt Publishing, October 2014 Oracle Press, October 2014 By Seb Rose, Matt Wynne, and Aslak Hellesoy Pragmatic Bookshelf, February 2015 This book will show you how to perform Java EE 7: The Big Picture explores the many key tasks with the NetBeans IDE, entire Java EE 7 platform in an all- Teams working on the Java Virtual uncovering more about mobile, desk- encompassing style while examining Machine (JVM) can now say goodbye top, and enterprise Java along the way. each tier of the platform in enough forever to misunderstood require-

You will start by creating Java projects detail so that you can select the right ABOUT US ments, tedious manual acceptance and learning how to refactor and use technologies for specific project needs. tests, and out-of-date documentation. NetBeans tools to increase developer In this authoritative guide, Java expert Cucumber—the popular open source efficiency. You then get a walkthrough Danny Coward walks you through the tool that helps teams communicate of how to create a desktop application, code, applications, and frameworks that more effectively with their custom- and then JavaFX, mobile applications, power the platform. Take full advan- ers—now has a Java version, and the and how to use external services. Having tage of the new capabilities of Java EE 7, best-selling Cucumber Book has been seen how to create many different types increase your productivity, and meet updated to match. It has the same good of applications, you are then shown how enterprise demands with help from this advice as the earlier book about how to to test and profile them before storing Oracle Press resource. deliver rock-solid applications collab- them in revision control systems such as oratively, but with all code completely Git or Subversion. Finally, you will learn rewritten in Java. New chapters cover how to extend NetBeans itself by adding blog features unique to the Java version of new features to the IDE. Cucumber, and reflect insights gleaned by the Cucumber team since the original book was published. 12

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 COMMUNITY JAVA IN ACTION JAVA TECH //20 years of java //

{THE MASTERS SPEAK} ABOUT US The code masters behind Java’s success discuss what has surprised them most over the years and what innovations are coming in the years ahead.

In the history of language development, example, was the language 15 years ago, but has made in two key areas: advancing the language “crossing the chasm” refers to the stage at which a seen its popularity decline rapidly during the last and optimizing the (JVM). language breaks out of a niche in which it was used decade—largely under pressure from Python. With this work in mind, we sat down with John only by aficionados and hobbyists and begins its Java, however, crossed the chasm and con- Rose, JVM architect at Oracle, and Mark Reinhold, journey into the programming mainstream. tinued to thrive in the mainstream. It has been chief architect of the Java Platform Group at blog Languages that cross the chasm become robustly healthy for two decades. In fact, by Oracle, and asked them to tell us what has most widely used. While they are assured of a almost all measures, its popularity continues to surprised them in their work on Java during these prolonged period of popularity, they are not grow. I attribute this success to the substantial last 20 years and what lies immediately ahead for guaranteed good health and long life. Perl, for investment Sun, Oracle, and various partners the language. —Ed. 13

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015

TWENTY YEARS OF INNOVATION COMMUNITY

A CONVERSATION WITH JAVA IN ACTION JOHN ROSE With Projects Valhalla and Panama, the JVM continues JAVA TECH to add useful features. BY TIMOTHY BENEKE

ny celebration of Java would be incomplete without

a discussion of the remarkable versatility of the JVM, ABOUT US which now hosts numerous languages such as Clojure, Groovy, JRuby, Jython, Kotlin, and Scala. JVM Architect AJohn Rose, whose history with Java dates back to his days at in 1995, contributed to the design of Java inner classes, the initial port of Java HotSpot VM to SPARC, and the Unsafe API. His work enhanced the performance of the HotSpot and OpenJDK stack, affecting everything from hardware architec- ture to code generators, libraries, and programming languages. He is currently the lead engineer of the Da Vinci Machine Project, a part of the OpenJDK effort, and the JSR 292 Specification Lead, responsible for specifying new support in the JVM standard for dynamic invocation and related facilities, such as type profiling blog and improved compiler optimizations. We spoke with him to get Rose’s first project on the JVM was designing and implement- his take on the past and future of the JVM. ing inner classes for Java 1.1.

PHOTOGRAPHY BY BOB ADLER/GETTY IMAGES 15

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: Tell us a little about your history with Java on the Java language.” James Gosling had a Java problem—

and the JVM. how to do method pointers and delegation—and asked for COMMUNITY Rose: I sometimes refer to myself as a “Lisp refugee” because my help. So I designed and implemented inner classes for I spent some of my early years happily programming in Lisp, Java 1.1. So I got onboard fairly early. which is a managed language with garbage collection and Because I’ve mentioned two of the main designers of Java safe dynamicity, with safe typing in a rich library. Like many who are not currently on the Java team, I should also mention language geeks, I invented my own Lisp VM, which I used Guy Steele, who is at Oracle Labs and has been instrumental successfully at Sun on a couple of projects. and is even now helping us think through the value type pro- Then Java exploded on the scene in the mid-1990s and posals for the JVM, which are part of Project Valhalla. So the JAVA IN ACTION I discarded my own VM and joined the Java project as one influence of the original designers of Java is still being felt. of the engineers who onboarded the HotSpot performance engine. I remember Bill Joy calling me “fresh meat” when I Java Magazine: Do you still do any coding yourself? joined the project and saying, “We need someone to work Rose: I still do code, even in C++. At Oracle I’ve been pri- marily concerned with the Java HotSpot VM and especially with its just-in-time [JIT] compiler and, of course, with the implementation. I was the main implementer of JSR 292, JAVA TECH the invokedynamic construction. I wish I could say that I code a lot. I mostly content myself with doing small proto- types to prove that things are possible, and I review other people’s core code. I have fun hammering out architectural documents with some really brilliant people in the organiza- tion. We have a good community, not only of coders whom ABOUT US I interact with all the time, but also hardware and software designers, theorists, and other folks who are trying to figure out the next great thing for Java. I’ve had two really good cod- ing sessions in the last couple of months. One was a proof of concept in Java for a way of doing value types, and another involved solving a C++ puzzle that should let us structure our Java HotSpot VM code better. There’s a good prospect that Java will naturally grow to assume more tasks that are currently being done with C++. When I’m frustrated with using C++, it’s usually because I’m building some part of the JVM that needs to be done right. When people on the team commiserate with each other blog about C++ and how come we have to do C++ when everybody around us is using Java on the VM, we are fond of saying that we do C++ coding so that millions of other people won’t have to. 16

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: Give us some historical perspective on “invokedynamic” instruction.

the JVM. But it took a good five years to implement, because we had COMMUNITY Rose: The original authors of Java understood that they could a lot of ideas about what dynamic invocation might look like not aggressively solve problems all at once, so they addressed and the design went in various directions. Our first prototype them in a layered manner. They not only invented Java but took some wrong turns, as the experts in the JSR 292 Expert also the virtual machine and, in particular, the bytecode and Group [in the —Ed.] pointed out. So object architecture that the Java compiler compiles to. We it was redesigned and came out in JDK 7 and has been an think of these things as bytecodes for Java, but there’s a lot important part of the stack ever since then. invokedynamic more to them—they have their own identity and their own is a completely general invocation Swiss army knife that lan- JAVA IN ACTION special powers, so we can think of bytecodes as a very power- guage implementers can use to implement not only dynamic ful and tastefully designed execution model in its own right. method invocation but also some kinds of static invocations The earliest versions of the JVM manual made it clear that that were not possible in the previous instructions. So it hit a the bytecodes were not sweet spot. It gives you full just replicating Java but JAVA VS. C++ access to the JVM’s capabili- could actually support other ties and full flexibility to the languages. And whether “People on the team commiserate with each other about C++: language implementer JAVA TECH people took the hint from ‘How come we have to do C++ when everybody around us is who’s working on top of the the architecture manual or JVM. To make a proof of because they perceived that using Java on the VM?’” concept, we had early the bytecodes were very involvement with Charlie inviting for such purposes, Nutter, the lead on JRuby, from the beginning, devel- who accelerated several ABOUT US opers began writing other languages for the JVM. Just a few prototype implementations of JRuby using invokedynamic. years after Java began, there were literally hundreds of known So we had dynamic language people involved extremely early. language implementations running on top of the JVM. There In recent years, Oracle has created a brand-new JavaScript were versions of Scheme, like Kawa, that came out very early, implementation called Nashorn [part of JDK 8 —Ed.], which and even today developers are continually inventing new lan- is a high-performing JavaScript engine that runs on top of guages to run on the Java bytecodes. It’s extremely exciting. the JVM, and was designed from the start to build on top of invokedynamic. Java Magazine: How has the JVM developed and changed over I want to make it clear that when you add a change to the the years? bytecode architecture—and this holds for the future—it can Rose: Around 2005, Sun Microsystems got serious about take years to think around and finally come to a good design. adding a new invocation mode in the JVM to support dynamic And once we’re committed to an implementation, it can take languages. We realized that our invocation modes were more years to establish the optimization dynamics of the blog all organized toward static typing and Java in particular, design. That’s one reason we go very slow in JVM evolution. and we wanted to add a new invocation mode or methods As James Gosling said recently at JavaOne, “We don’t want to that would more directly support dynamic languages and do things until we know we can do them right—in Java and semantics. So before we had any details, we called it the on the JVM.” 17

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: Where is the JVM headed? struct that looks like a class, but when you use it, it feels like

Rose: Oracle and the Java community are making serious an int. COMMUNITY investments in two new OpenJDK projects, Valhalla and The addition of value types also makes it easier for other Panama. Project Valhalla is ultimately aimed at closing the languages to migrate to the JVM. It no longer forces languages divergence between references and primitives so that users that have other datatypes to conform them to the JVM. can define new primitive-like types, which we call “value They can create datatypes to reflect their natural datatypes. types.” Java doesn’t have a complex number or an unsigned They can do that today, but at the cost of a pointer and a int type. It doesn’t have a 128-bit integer type, but with value storage allocation. types we will be able to create all of these as library code, not JAVA IN ACTION as VM intrinsics. That’s a big vision. A basic physical reason Java Magazine: What is Project Panama? why we need this is because value types are natural units Rose: With Project Panama, we are creating a more robust for flatter, more compact data structures. You can look at interconnection with native code. Developers like Java our current Java architecture and say, “Suppose you don’t because it’s a friendly language to write in. But sometimes have value types, and suppose you’re not allowed to make they have to program in C or C++ because, for example, new primitives. Surely you can use classes to make 128-bit there’s a low-level system library with the C API. So they have integers and unsigned ints and complex numbers.” This is to pull out their C editor and include some header files and JAVA TECH something people do. But the problem is that it’s tied up start coding up in C. To weave that into their Java project, they with this object-oriented data model that is native to Java, have to write a bunch of Java Native Interface [JNI] code. But which puts pointers everywhere. And it turns out that once JNI is intentionally difficult to use. In its early days, Java was you make an object that’s reachable by a pointer, it’s hard to fighting to differentiate itself and needed to maintain a- cer get rid of the pointer. There’s a class tain amount of integrity and control over its own execution. of effects called “identity semantics” So the JVM was pretty unwilling to share trust with native JVM LANGUAGES ABOUT US that makes it difficult or impossible libraries. If you’re going to attach a native library, you might “Clojure is a mad-scientist library of how for compilers to ignore the pointer. If have to sign up for months of engineering work to create the to rethink concurrent programming with this were not a problem, Java wouldn’t necessary JNI bindings. need primitive types with everything So to enter the JVM world from the C world, you had to persistent data structures in the setting of being an object. With value types, either leave your C behind or bring it in at great cost. It’s an idiosyncratic Lisp-like language.” the same performance feel that you like an import duty. Java now has a stable place in the com- get from an int, you’ll get from a puting world, so it would be helpful to Java to have a more complex number. The same things tax-free entry from the C world to the Java world—that’s that make you hesitate before using Project Panama. a Java.lang.Integer on your data also push you away Here’s a picture: If Java is the Pacific Ocean and C is the from using a Java map complex class. But once the complex Atlantic Ocean, Panama offers an easy bridge or canal to con- becomes a value type instead of an object type, it loses its nect the two great bodies. I posted a manifesto on my blog a blog indirection—it gains flat data representation, and the perfor- few months ago called “The Isthmus in the VM” that lays mance profile feels like an int. out the risks and rewards of connecting Java and C. I’m happy In fact, that’s our slogan for value types: “Codes like a class, to say that Project Panama is making good progress. So works like an int!” You define your complex in a library con- JVM users should one day enjoy not only a wide variety of 18

ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 languages with more and more pow- IN THE JVM formers in the market today, because

erful datatypes, but also the ability the bytecodes are not only a good COMMUNITY to resort to C libraries with much less “Bytecodes are not only a good execution format but they’re a good overhead. execution format but they’re a good representation of a program that can be representation of a program that can manipulated in its own right. Java Magazine: What’s happening with bytecode transformers? be manipulated in its own right.” Java Magazine: Tell us about the role of Rose: Let me first provide some back- the JVM Language Summit. ground. The idea of having a flexible vir- Rose: When we started doing the JVM JAVA IN ACTION tual machine that runs at high speeds is Language Summit in 2008, we realized fairly old. Pascal achieved some portability using p-code and that there was a substantial community doing very interest- if you look at the early Java papers, they acknowledge a debt ing things just on the bytecodes. So it was a fun idea to have to previously existing bytecode and virtual-machine instruc- them all gather together. They talk in a very specialized kind tions. One reason that Java’s bytecode design has been of technical language—these are people who speak bytecode an extremely successful VM instruction set is that it hides and are interested in what the bytecodes could do for them. enough detail about the underlying machine, so that it can They are knowledgeable about compilation techniques that JAVA TECH be easily moved and re-executed from machine to machine. would take a high-level language into bytecodes. We’ve met It also has security properties that were not present in previ- once a year since 2008, and it’s usually the best conference ous bytecodes. In other words, the information-hiding aspect that I go to each year because the attendees care passion- of the bytecodes implies a secure ability. It means that your ately, not only about Java but also about efficiently imple- bytecodes can, in certain situations, be proven by a verifier to menting languages on top of Java bytecodes. As a result, not subvert the . We don’t allow unsigned or pos- we’ve been able to slowly evolve the virtual machine so that it ABOUT US sibly hostile code to run on the JVM, because the bytecode is will serve more and more languages. hardened against such attacks. By the way, we take very seri- Of course, now we have Clojure, Groovy, Jython, JRuby, ously any reports of loopholes or cracks in the armor, and we Scala, and other established languages. Scala is a wonder- patch them up as vigorously as we can. It’s one of our priori- ful mad-scientist library of excellent language ideas. And ties to keep the attack surface as clean as possible. Clojure is a mad-scientist library of how to rethink concur- Our bytecode set is not just an executable format but is rent programming with persistent data structures in the also a clear expression of the abstract structure of a program. setting of an idiosyncratic Lisp-like language that some Users can perform a neat trick and transform bytecodes. people find extremely compelling when it fits their problem So, people have written all sorts of really ingenious byte- space.