Java Magazine 2013 11-12 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

//table of contents /

COMMUNITY
COMMUNITY 40
03 Enterprise Java
From the Editor Database DevOps

JAVA IN ACTION
05 with MySQL, Hudson,
Java Nation Gradle, Maven, and Git
JavaOne recap, plus news, Produce higher-quality
people, and events software with DevOps.

17 47
JCP Executive Series Enterprise Java
Q&A with Patrick Adding a Member to
Curran Your Development Team

JAVA TECH
The JCP chair on charting The best and worst ways to
the future with JCP.next manage the addition of a new
team member
JAVA TECH 50
28 Enterprise Java
Java Architect Concurrency Utilities
Agile Adjustment for Java EE

ABOUT US
Venkat Subramaniam Learn how to best execute
explores the subtleties of tasks using application server
agile development. concurrency services.
31 62
Java Architect Fix This
Diabolical Java Take our generics code
Performance Tuning challenge!
Lessons in what not to do
22 28 EST
NT
57
SMARTEST

B
33 ME
Java Architect Our special E LOP Mobile and Embedded

S
V
section on DE

CE
Java Concurrent P R A C TI INTERNET OF

HOUSE ON THE
best practices
Animated for development THINGS 101
Java Champion Victor Grazi Explore concepts relevant
includes articles on
to the Internet of Things

STREET
on writing better concurrency agile, performance tuning,
applications by creating an embedded
concurrency, DevOps, and
team dynamics. application. blog

The Internet of Things meets home


automation with Java-based openHAB.

COVER ART BY WES ROWELL; PHOTOGRAPHY BY TON HENDRIKS


01
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
EDITORIAL
Editor in Chief
Caroline Kvitka
Community Editors
PUBLISHING
Vice President
Jeff Spicer
Publisher Java Skills
#1 Priority
Cassandra Clark, Sonya Barry, Jennifer Hamilton +1.650.506.3794
Yolande Poirier Associate Publisher and Audience

JAVA IN ACTION
Java in Action Editor Development Director
Michelle Kovac Karin Kinnear +1.650.506.1985
Technology Editors
Janice Heiss, Tori Wieldt ADVERTISING SALES
President, Sprocket Media
Contributing Writer Kyle Walkenhorst +1.323.340.8585
Kevin Farnham

Of Hiring Managers
Western and Central US, LAD, and
Contributing Editors Canada, Sprocket Media
Claire Breen, Blair Campbell, Karen Perkins Tom Cometa +1.510.339.2403
DESIGN Eastern US and EMEA/APAC,
Senior Creative Director Sprocket Media
Francisco G Delgadillo Mark Makinney +1.805.709.4745

JAVA TECH
Senior Design Director Advertising Sales Assistant
Suemi Lam Cindy Elhaj +1.626.396.9400 x 201
Design Director Mailing-List Rentals
Richard Merchán Contact your sales representative.
Contributing Designers RESOURCES
Jaime Ferrand, Arianna Pucherelli
Production Designers
Oracle Products
+1.800.367.8674 (US/Canada) Get Certified with Oracle University
Sheila Brennan, Kathy Cygnarowicz Oracle Services
+1.888.283.0591 (US)
Prepare with Java experts

ABOUT US
Oracle Press Books
oraclepressbooks.com
In the classroom or online
ARTICLE SUBMISSION
If you are interested in submitting an article, please e-mail the editors. Pass or retest for free
SUBSCRIPTION INFORMATION
Subscriptions are complimentary for qualified individuals who complete the
subscription form. And save up to 20%
MAGAZINE CUSTOMER SERVICE
[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.
Copyright © 2013, 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

Preview Now
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 with a free subscription price by
Oracle, 500 Oracle Parkway, MS OPL-3C, Redwood City, CA 94065-1600. Source: from Dice.com’s “Dice Report”; “January 2013: Repeat Priorities”

Digital Publishing by GTxcel


02
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//from the editor /

COMMUNITY
F

JAVA IN ACTION
FIND YOUR
JUG HERE

JAVA TECH
uturistic, automated homes are becoming a reality. I grew up watching The Jetsons, a cartoon about a
space-age family living in 2062 with robotic housekeepers, wacky inventions, and personal spacecraft. Now, My local and global JUGs
50 years since it first aired, some of the show’s predictions are looking closer to reality. are great places to network
both for knowledge and work.
If you attended JavaOne in San Francisco, you couldn’t miss the buzz about the Internet of Things (IoT)—
My global JUG introduces
with predictions of a world where billions of devices will be connected to the internet. It’s here, and Java is me to Java developers all
playing a big part. You were also sure to see robots at the event, whether they were NAO robots, robotic fish, or over the world.

ABOUT US
Lego bots. There was also much buzz about the Raspberry Pi, which had its own developer challenge. Régina ten Bruggencate
JDuchess
Home automation is a prime example of IoT. In this issue’s “Smartest House on the Street,” we take you in-
side a modern home where devices and applications are integrated throughout, using a Java-based software LEARN MORE
environment called openHAB (a 2013 Duke’s Choice Award winner).
Need to get up to speed on Java and IoT? Read Eric Bruno’s “Internet of Things 101” to see why Java, which
was born on an embedded device, is in a great position to become the standard for IoT development.
No matter what type of project you’re working on, we know that you
EST
T
need to be the best developer you can be. So in this issue we bring you //send us your feedback /
B

EN
O PM
L
VE a special section focused on development best practices. Look for the We’ll review all
S

DE
CE

P R A C TI suggestions for future


icon on the left to find articles covering agile development, perfor-
improvements.
mance tuning, concurrency development, DevOps, and team dynamics. Depending on volume,
What futuristic projects are you dreaming up? Let us know. some messages may
not get a direct reply. blog
Caroline Kvitka, Editor in Chief BIO

PHOTOGRAPH BY BOB ADLER


03
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation / javaone 2013 //

COMMUNITY
The 18th
JAVAONE

JAVA IN ACTION
Attendees from more than 92 countries
attended JavaOne 2013, where they chose
from more than 400 sessions; hung out in a

JAVA TECH
Codegarten; participated in a Raspberry Pi cod-
ing challenge; and attended educational and
networking events. What’s more, the America’s
Cup sailing race added to the festive atmo-
sphere of JavaOne—and culminated with a
historic comeback win by ORACLE TEAM USA.
The conference kicked off at San Francisco’s

ABOUT US
Moscone Center with the Strategy keynote
by Oracle’s Peter Utzschneider and Nandini
Ramani. The theme, “Make the Future Java,”
was unchanged from last year’s theme, for
good reason, Utzschneider said. “There is a lot
going on in the industry, with massive shifts
Clockwise from and innovation happening that pose huge chal-
top: A festive lenges and opportunities for Java.” The goal is
atmosphere at to make Java better, stronger, more robust, and
the Taylor Street relevant for decades to come.
Café; Peter The combination of mobile and social is cre-
Utzschneider ating an enormous amount of data in many
talks about forms, with growing volume and velocity.
the Internet
of Things; Utzschneider said that between 10 and 50 bil-
Nandini Ramani lion nonhuman-driven devices will be coming blog
discusses on the internet in the next two years. “This is
convergence. about the Internet of Things [IoT],” he said. “It
will be a major game changer for Java develop-
ers and the larger community.”
PHOTOGRAPHS BY ORANGE PHOTOGRAPHY 05
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation / javaone 2013 /

COMMUNITY
Ramani discussed unifying the
Java platform. “With Java SE 8, we
will release the Compact Profile
TECHNICAL KEYNOTE

JAVA IN ACTION
and will replace Connected Device
Configuration, so we will have one less
implementation. We are also increas- Oracle’s Mark Reinhold kicked off the JavaOne Technical key-
ing commonality both from an API and note by quoting James Gosling. For Java to thrive, it must main-
a language perspective.” tain what Gosling called the “feel of Java” and retain the key
Ramani also touched on the IoT. values of readability, simplicity, and universality.
“Everyone believes that there is a “If we keep those,” said Reinhold, “then Java will remain not
need for an open standard platform just productive but fun. It is not enough to simply add popular

JAVA TECH
for the Internet of Things space that is features each year.” Reinhold went on to focus on many inno-
coming—Java is the logical choice to vations in Java. Here are some highlights:
address this market,” she said. Lambda expressions. Reinhold called lambda expressions the
single largest upgrade to the programming model ever. “This
is the first time we have done a carefully coordinated coevolu-
tion of the JVM [Java Virtual Machine], the language, and the
libraries all together—and the results still feel like Java,” he

ABOUT US
said. Oracle’s Brian Goetz came on stage and said that lambda
expressions will “change the way we all program in Java every
day. Java has always given us good tools for abstracting over
datatypes. I wanted to do better in abstracting over patterns of
behavior—that’s where lambda comes in.”
DukePad. Oracle’s Jasper Potts and Richard Bair demoed the
Watch Strategy keynote highlights. DukePad, a do-it-yourself tablet based on the Raspberry Pi and
Oracle Java SE Embedded 8. The DukePad uses Raspbian Linux
as the OS and an OSGi-based JavaFX environment.

Top to bottom:
Richard Bair plays
chess; Jasper
Potts shows off
the DukePad;
blog
Mark Reinhold
talks about
Watch Technical keynote highlights. lambdas.

PHOTOGRAPHS BY ORANGE PHOTOGRAPHY


06
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation / javaone 2013 /

COMMUNITY
FREESCALE

JAVA IN ACTION
AND THE IoT
Geoff Lees of Freescale Semiconductor
kicked off the Java Community keynote
to a standing-room-only crowd. He

JAVA TECH
presented a vision of how the Internet
of Things (IoT) might become a reality.
“The microcontroller community is
rapidly moving to adopt Java, and we

Community
need your help,” said Lees.
The IoT is changing the way the
Geoff Lees presents an semiconductor industry is thinking

Keynote
Internet of Things vision.

ABOUT US
about technology, Lee said, in terms
of processing node transitions, greater
utilization of advanced sensor technologies, integration of those
technologies, and rapid adoption of low-power technologies both
from processing and design techniques. Advances in signal analog Oracle’s Donald Smith followed Freescale Semiconductor’s Clockwise
integration and the IoT are bringing these things closer. Geoff Lees at the Community keynote with a look back at from left:
recent JavaOne conferences. JavaOne 2011 was about mov- Henrik Stahl
“Instead of the next few years, we’re thinking about how to do
ing Java forward and rebooting the infrastructure after the
and Stephen
all of this in the next few months,” said Lees. The key to creating Chin play
a secure IoT lies with Java developers, he said. Java-based edge Java SE 7 launch. JavaOne 2012 focused on innovation and with Lego
nodes offer the potential to have secure encryption and authenti- showing Java’s role in major tech segments such as the bots; Stephan
cation services throughout the network. Developing those in other cloud, big data, the Internet of Things, and open source. Janssen
environments will be locally difficult, will not be global, and will “This year,” Smith said, “we take one step beyond all that, talks about
not reach the tipping point required for the IoT to develop. and celebrate the end user and application developers. Devoxx4Kids;
Lees said that Freescale and Oracle are collaborating to develop We want to show some inspiring applications being built Aditya Gupta
thanks to the hard work of the Java ecosystem.” shares his
a platform for software and hardware models for both edge nodes Minecraft blog
and a wide variety of gateway solutions. “We’re working on opti- Over the course of the keynote, a number of innovators programming
mizing Java together and bringing Java functionality further into joined Oracle’s Henrik Stahl on stage. skills.
the network.” Java Champion Stephan Janssen talked about 2013
Duke’s Choice Award winner Devoxx4Kids, a program that
PHOTOGRAPHS BY ORANGE PHOTOGRAPHY AND PETER PILGRIM
07
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation / javaone 2013 /

COMMUNITY
JAVA.NET POLL
teaches computer programming to
children between 10 and 14 years
MOST IMPORTANT JAVAONE TRACK

JAVA IN ACTION
old. He offered the Devoxx4Kids
teaching materials to any Java user
In the weeks preceding JavaOne, a Java.net poll asked the Java com-
group that would like to hold an
event for children.
munity to consider the eight different technology tracks at JavaOne
Oracle Academy’s Alison and select the most important one. The poll ran for two weeks, dur-
Derbenwick Miller described the ing which 304 votes were cast in response to the question: “The most
academy’s outreach efforts that important track at JavaOne 2013 will be . . . .” Here are the results:
affect 2.5 million students in 102 countries.

JAVA TECH
Aditya Gupta, a 10-year-old Minecraft hacker, 30%
entertained the audience by showing off enhance-
Client and Embedded Development with JavaFX
ments he made to the Minecraft source code (mak-
ing pigs fly, creating never-ending cascading explo- 21%
sions, and otherwise having fun with the code). It’s all important!
Two Duke Segway robots appeared on stage
and strutted around under the guidance of Java 16%

ABOUT US
Champion Stephen Chin. Securing Java
Java Champion Paul Perrone (via video) showed
off Java-powered cars. 7%
Drew Hylbert of Opower shared how Java technol- Core Java Platform
ogy is used to enable consumers to save energy.
Mike Marzo, a technology fellow at Goldman 7%
Sachs, discussed the value of the 100 million lines Emerging Languages on the Java Virtual Machine
of Java code that Goldman’s developers have writ- 7%
ten over the years.
Java EE Web Profile and Platform Technologies
Finally, James Gosling (top left), the “father
of Java” and chief software architect at Liquid 6%
Robotics, appeared and remarked that Aditya Gupta Java Web Services and the Cloud
made him feel that he, too, should be a Minecraft
hacker. Gosling showed the view of Hawaii from one 4%
of Liquid Robotics’ Wave Glider bots in the ocean Java Development Tools and Techniques blog
and explained in detail how it all worked.
3%
The Community keynote offered a strong sense of
renewal and pride in what Java has accomplished Edge Computing with Java in Embedded, Smartcard, and IoT Applications
and where it’s headed.
PHOTOGRAPH BY PETER PILGRIM
08
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation / javaone 2013 /

COMMUNITY
JAVA EMBEDDED CHALLENGE
FOR RASPBERRY PI

JAVA IN ACTION
Ride Goes On
Despite heavy rains
Clockwise
from left:
on the Saturday Vinicius Senger
before JavaOne, describes the
the Geek Bike Ride Raspberry Pi’s
went on, with 12 configuration;
determined riders sensors on

JAVA TECH
making the trip from Raspberry Pi,
Fisherman’s Wharf Gemalto, and
Beagle boards;
over the Golden Gate Yara Senger
Bridge to Sausalito. The Java Embedded discusses the
Talk about Java Challenge for goals of the
persistence! Raspberry Pi at challenge.
JavaOne provided

ABOUT US
an opportunity for
conference attendees with sensors, Raspberry Pi, Arduino, and
to build embedded other boards. Experts and mentors gave
projects. The two-day presentations and coached the teams
challenge kicked off while they developed their applications.
with a series of lectures that introduced “Our main goals were achieved,” said
the Raspberry Pi and projects that use it. Yara Senger. “People had fun coding until
Globalcode’s Vinicius Senger, who ran 11 p.m. despite the great parties [going on],
the event with Globalcode’s Yara Senger, and developed amazing projects in just a
described the Raspberry Pi’s layout and its couple of days.”
configuration with other boards. He also The teams developed seven remote-
showed off an embedded panel that he controlled applications: a heart monitor
had built, which included Arduino, Beagle, application using Google Glass, a radio-
and other boards. He added sensors to controlled car application, a home auto-
monitor alcohol in breath, heart rate, dis- mation platform, a sobriety field tester, a blog
tance, and sound. remote control using any phone, a load-
Over three days, attendees built Oracle balancing cloud application, and a burglar
Java SE Embedded applications integrated alarm with voice/text alerts.

PHOTOGRAPHS BY ARUN GUPTA AND YOLANDE POIRIER


09
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation / javaone 2013 /

COMMUNITY
THE POWER OF COMMUNITY Product News

JAVA IN ACTION
The fact that Meanwhile, Timon Veenstra,
community is lead developer for AgroSense The Java SE 8 Specification and JDK 8,
a fundamental (a 2012 Duke’s Choice Award its official Reference Implementation,
aspect of Java’s winner), held a session where are expected to be available in March
reach into people’s an airplane controlled by a 2014. The key features of Java SE 8 and
lives was illustrated NetBeans application flew in the JDK 8 are Project Lambda (JSR 335),
in a Sunday JUG session hall. the Nashorn JavaScript engine, a new

JAVA TECH
forum presented by Another Duke’s Choice Award Date and Time API (JSR 310), a set of
Morocco JUG leader winner was JFrog’s Bintray, a Compact Profiles, and the removal of
Badr El Houari and community centered on redis- the “permanent generation” from the
JUG-Africa leader tributable software binaries. Java HotSpot VM.
Max Bonbhel. Bintray provides developers with Java ME 8 is expected to be available
Timon Veenstra Badr El Houari El Houari success- the knowledge of how others are in March 2014, in conjunction with the
fully launched consuming their software, and Java SE 8 Specification. New features

ABOUT US
The importance of commu- the first JMaghreb Conference also provides developers with a in Java ME 8 include Java language and
nity was vividly illustrated in November 2012, with searchable resource for finding API alignment with Java SE 8; support
throughout JavaOne 2013. The 30 sessions, 18 speakers, and software for specific needs. for modern web protocols; a compre-
conference opened on Sunday, 850 attendees. Bonbhel had There are many different hensive application model that will
September 22, with NetBeans just returned from the third programming languages and enable both simple, single-use devices
Day and Java user group (JUG) JCertif Conference, which toolkits, but in its community and more-complex deployments;
forums that covered everything was attended by more than aspect Java is unique. advanced security; standard APIs for
from starting and maintaining 1,800 developers from 20 dif- power management; and interaction
a JUG to GlassFish to the Java ferent countries. with a broad set of standard periph-
Community Process (JCP) and The NetBeans community was erals. Oracle Java ME Embedded 8
the Adopt-a-JSR and Adopt- also fully engaged at JavaOne. will be the Oracle implementation
OpenJDK efforts. The last day of Four Duke’s Choice Awards of the Java ME 8 standard. Oracle
the conference began with the went to applications built on Java ME Embedded 8 Early Access is
Community keynote address top of the NetBeans platform. now available as a binary runtime for
(see page 7). In between there Sean Phillips, of a.i. solutions, Raspberry Pi Model B (ARM11) and ST blog
were plenty of community- spoke at the Community key- Microelectronics STM32F4DISCOVERY
related sessions, panel discus- note about the NetBeans- (ARM Cortex-M4).
sions, and evening Birds-of-a- based GEONS ground support James Gosling at NetBeans Day
Feather (BOF) sessions. system his team developed.
TIMON VEENSTRA PHOTOGRAPH BY TON HENDRICKS
10
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation / javaone 2013 /

COMMUNITY
PARTNER NEWS

JAVA IN ACTION
Oracle introduced the Oracle Java Platform Integrator program, which
gives partners the ability to customize Oracle Java ME Embedded and
Oracle Java SE Embedded to reach different device types and market
segments.
Gemalto is working with Oracle and V2COM, a developer of smart From left: Mohamed Taman, Gil Tene (with Heather VanCura), Brian Goetz
grid systems, to deliver a flexible smart-energy solution. This platform

Java

JAVA TECH
combines Gemalto’s Cinterion modules, Oracle Java ME Embedded, The 11th annual Java Community
Oracle Java SE Embedded, the Oracle Utilities Meter Data Management Process (JCP) Program Award recipi-

Community
solution, and V2COM’s Intelligenceware Suite. ents were honored during JavaOne.
Qualcomm Technologies and Oracle have collaborated to bring The categories and winners were

Process
Oracle Java ME Embedded to key chipsets in Qualcomm Technologies’ JCP Member/Participant of the Year:
Internet of Everything portfolio. Oracle Java ME Embedded support is Gil Tene, Azul Systems
currently available on QSC6270-Turbo, and Oracle and Qualcomm are According to the JCP, “[Tene] has

Awards

ABOUT US
working together on expanding this to MDM6x00 and MDM9x15, as worked diligently to provide clear
well as other chipsets. advice on matters of software patents,
Freescale Semiconductor has joined the OpenJDK community and IP, and licensing that seeks to benefit
will collaborate with Oracle and others to help evolve the Java platform both nonprofits/individuals as well as organizations with vested com-
and optimize Java for Freescale i.MX ARM-based applications proces- mercial interests in Java.”
sors. Freescale has also joined the Java Community Process (JCP) and Outstanding Spec Lead: Brian Goetz, Oracle
intends to work with Oracle and other JCP members on future Java The JCP recognized Goetz for “tirelessly working away at an incredibly
specifications for small and large devices. complex JSR: JSR 335, Lambda Expressions for the Java Programming
Linaro has also joined the OpenJDK community and is already con- Language.”
tributing to porting and optimizing Java for 64-bit ARM processors. Most Significant JSR: JSR 335, Lambda Expressions for the Java
Square has also joined the OpenJDK community and is actively col- Programming Language
laborating with Oracle and others in the community to enhance the According to the JCP, JSR 335 “brings Java kicking and screaming into
Java programming language, Java Virtual Machine, and core libraries. the modern programming language age . . . .”
The Raspberry Pi will now ship with JDK 7. Future Raspbian images Outstanding Adopt-a-JSR Participant: Mohamed Taman and Faissal
will ship with Java by default, and existing Raspberry Pi users can install Boutaounte, Morocco JUG and EGJUG blog
the new Java support by typing the following: Taman and Boutaounte were praised “for adopting JSR 339, JAX-RS
sudo apt-get update && sudo apt-get install oracle-java7-jdk 2.0 specification, along with many other JSRs. One JIRA issue filed by
Morocco JUG on JSR 339 was classified as a ‘release-stopper.’”

11
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation /

COMMUNITY
JAVA CHAMPION PROFILE
BEN EVANS
open and playful BASIC in onboard ways to have fun with respect to your
17

JAVA IN ACTION
15 18 mind is essential ROM, soon fol- and relax. daily life?
for proper creativ- lowed by Z80 Java Magazine: Evans: I really like
ity. So, I would tend assembler. What happens on the jacket, and it’s
to have concerns Java Magazine: your typical day off? become my most
about some of the What was your first Evans: I don’t have frequently worn
21 22 23 24 connotations that professional pro- many days when article of clothing
usually go along gramming job? I don’t do some that isn’t black.
with the phrase Evans: Despite work, but if I’m in Java Magazine:

JAVA TECH
Ben Evans is a
grow up. my early start, it London, I’ll try to What, in your view,

Java Advent
leader of the
Java Magazine: took me 12 years enjoy the side of is most significant
London Java
When and how did to figure out that the city that most about the recent
Community (LJC),

Calendar a member of the


Java Community
Process (JCP), an
you first become
interested in
computers and
people would pay
me to program. My
first programming
people don’t nor-
mally see because
they’re at work dur-
Java EE 7 release?
Evans: To pick just
one technology, I’d
The Transylvania Java User Group
author and speaker, programming? job was building a ing the day. say the JSON sup-

ABOUT US
is seeking contributions for the Evans: My parents website for a surf Java Magazine: port. However, if we
second edition of the Java Advent and a founder of
felt very strongly shop/hotel/night- What “side effects” think about Java EE
Calendar, a series of 24 Java-related startup jClarity.
that computers club. I got paid in of your career 6, it took a while for
technical articles to be published He was named a
and programming wetsuits, room do you enjoy the the real benefits to
daily during the first 24 days of Java Champion in
were going to be and board, and a most? become well known
December. February 2013.
an important part bar tab. Evans: I love to across the industry
The Java Advent Calendar is based Java Magazine:
of the future, and Java Magazine: travel, so the —and I think the
on a special Christmas calendar that Where did you
gave me my own What do you opportunity to visit same will happen
is popular with children. Each day grow up?
machine for my enjoy for fun and friends and col- with Java EE 7.
the child selects a new window to Evans: I spent
eighth birthday, relaxation? leagues all over Java Magazine:
open and discovers the surprise— my childhood in
Evans: I like to go
Cornwall, England, in 1984. the world and talk What are you look-
typically a small toy or chocolate— Java Magazine: hiking, surfing in about my work is ing forward to in
hiding behind it. Help make the Java and studied
What was your the summer, and probably the best the coming years?
Advent Calendar a gift to Java devel- at Cambridge
first computer snowboarding in side effect. Evans: The unex-
opers by contributing an article to University, but blog
and programming the winter. I love to Java Magazine: pected things.
the calendar! I’m one of those
technologists who language? travel and usually Has being a Java Follow Evans on
Evans: ZX don’t have much Champion changed Twitter and read
believe that an
Spectrum 48K with trouble finding anything for you his blog.

PHOTOGRAPH BY JOHN BLYTHE


12
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation /

COMMUNITY
Smart Home Workshop
FEATURED JAVA USER GROUP at JCertif 2013
LYON JAVA USER GROUP

JAVA IN ACTION
Oracle Technology
Network spon-
sored a Smart
do encourage beginner speak- Home Workshop
ers to do a lightning talk during at JCertif 2013,
each event.” held September
“We also have a bigger event 9–15 in Brazzaville,
each year, Mix-IT, curated with Republic of the

JAVA TECH
the local agile group, where Congo.
we host a conference for two Firas Gabsi (above left), a passionate,
days with international speak- young Java EE and mobile engineer and a
ers and about 500 attendees,” professor of engineering at the Engineering
(Left) A traditional Lyon JUG meeting; a programming workshop Exbrayat notes. “We have more Institute in Tunisia, led the workshop.
than half of the talks about Attendees learned to integrate Oracle Java
The Lyon Java User Group was around whatsoever,” says agile methodology, innovation, SE Embedded with Raspberry Pi and other

ABOUT US
formed in 2009 after discus- Exbrayat. “So we did it to meet and mind-blowing new things equipment for home automation systems.
sions that took place between other people, and we had talks (robotics and 3-D printing).” “I didn’t know much about the Java
Alexis Hassler, Laurent Gayet, about Java of course, but also The monthly meetings pro- embedded technology, but now I have
Julien Ripault, and Cédric about the web and mobile. vide a great way to meet other acquired the basic knowledge that I will
Exbrayat on the French forum Now there are a lot of small developers. “It’s sad that so keep improving,” said Java engineer Yanhick
Developpez.com. It wasn’t too communities around, on every many people are missing this Keny, who was one of 80 participants.
long before the group con- language, and I like the idea opportunity,” Hassler adds. Give it a try! Download the project from
tacted Agnès Crepet, who soon that our energy has contrib- Learning about other tech- GitHub.
became a very active member uted to that.” nologies is also important to
of the Java user group (JUG). Lyon JUG normally holds one the JUG. “Java and its huge
Exbrayat notes, “Agnès is a meeting each month. In addi- ecosystem are an amazing
passionate developer. We were tion, the JUG sometimes holds value in the lives of developers,
very pleased to have her join programming workshops on but I’m really convinced that
us, and when she did she also topics related to that month’s we have to know other lan-
formed our Duchess group.” meeting. Crepet says, “I think guages and tools,” says Crepet. blog
“When we founded the JUG, we are a fairly traditional JUG “That’s why we speak about Git
there were no user groups with monthly events, but we or NoSQL in our JUG sessions.”
Gabsi demos one of the projects.

PHOTOGRAPHS COURTESY LYON JUG


13
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation /

COMMUNITY
Take Off
JANUARY 30–31
LILLE, FRANCE
This conference for web develop-

JAVA IN ACTION
ers and designers offers a range of
sessions on topics including web
servers, front end, frameworks, and
development techniques.

DevNexus 2014
FEBRUARY 24–25

JAVA TECH
ATLANTA, GEORGIA
The Atlanta Java User Group (AJUG)
has organized this Java conference
for the past eight years. It covers
Java topics including web technolo-
gies, architecture, big data, enter-
prise software, mobile, Java SE,

EVENTS
jDays

ABOUT US
testing tools, and methodologies.
NOVEMBER 26–27
GOTHENBURG, SWEDEN 8th Annual IndicThreads Pune
Jfokus FEBRUARY 3–5 This Java developers conference Conference
STOCKHOLM, SWEDEN offers sessions on Java SE, Java EARLY 2014
EE, frameworks and servers, front PUNE, INDIA
Jfokus, one of the premier European Java developer conferences, is end, web and mobile, trends and Web technologies, server side,
back for its eighth year. Held in Stockholm, Sweden, Jfokus consists future, solutions, case studies and big data, and mobile software
of six tracks including a subconference on embedded technologies. real-world experiences, and meth- development are the focus of
Conference topics include Java SE and Java EE, front end and web, odologies and tools. this conference.
mobile, continuous delivery and DevOps, the Internet of Things,
cloud and big data, future trends, alternative languages—such as Groovy & Grails eXchange
Scala and Clojure—on the Java Virtual Machine, and agile develop- DECEMBER 12–13
ment. Speakers include Dr. Venkat Subramaniam of Agile Developer, LONDON, ENGLAND
Jim Manico of WhiteHat Security, Martin Thompson of Real Logic, Industry-leading experts and devel-
and many more. opers from around the world gather blog
at this conference to learn and
share everything about the Groovy
and Grails ecosystem.
PHOTOGRAPH BY GETTY IMAGES
14
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java nation /

COMMUNITY
JAVA BOOKS

JAVA IN ACTION
JAVA WEBSOCKET JAVA EE 7 ESSENTIALS MAKING JAVA GROOVY PRO JSF AND HTML5
Java Spotlight PROGRAMMING By Arun Gupta By Kenneth A. Kousen By Zubin Wadia, Hazem Saleh,

JAVA TECH
Podcast
By Danny Coward O’Reilly (August 2013) Manning Publications and Allan Lykke Christensen
Oracle Press (August 2013) Get up to speed on the (September 2013) Apress (November 2013)
Learn how to build principal technologies Making Java Groovy is a Pro JSF and HTML5 shows
Listen to the Java dynamic enterprise web in Java EE 7, and learn practical handbook for you how to leverage the
Spotlight podcast for applications that fully how the latest version developers who want to full potential of JavaServer
interviews, news, and leverage state-of-the-art embraces HTML5, focuses blend Groovy into their Faces (JSF) and Ajax. This
insight for and from communication technolo- on higher productivity, and day-to-day work with Java. is not an entry-level tuto-

ABOUT US
Java developers. Hosted gies. Written by the leading provides functionality to It starts by introducing the rial, but a book about
by Roger Brinkley, this expert on Java WebSocket meet enterprise demands. key differences between building Ajax-enabled JSF
weekly show includes a programming, this book Written by Arun Gupta, Java and Groovy—and how components for sophis-
rotating panel of all-star offers practical devel- a member of the Java EE you can use them to your ticated, enterprise-level
Java developers. opment strategies and team, this book provides a advantage. Then, it guides rich internet applications.
detailed example appli- chapter-by-chapter survey you step-by-step through Written by JSF experts and
cations. Java WebSocket of several Java EE 7 realistic development chal- verified by established
Programming explains spec­ifications, includ- lenges, from web applica- community figures, this
how to design client/server ing WebSocket, Batch tions to web services to book provides reliable and
applications, incorporate Processing, RESTful Web desktop applications, and groundbreaking JSF com-
full-duplex messaging, Services, and Java shows how Groovy makes ponents to help you exploit
establish connections, cre- Message Service. them easier to put into the power of JSF in your
ate endpoints, handle path production. Java web applications.
mapping, and secure data.
You’ll also learn how to blog
encrypt web transmissions
and enrich legacy applica-
tions with Java WebSocket.

15
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
The Essential Source on Java Technology, the Java
Programming Language, and Java-Based Applications. By and for the Java community

Connect with the Audience


that Matters Most to Your Business.
Audience: Corporate and independent
developers, IT managers, architects,
product managers, and students

Circulation: Currently 165,000+

Click here to subscribe

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
COMMUNITY
JAVA IN ACTION
P
atrick Curran is chair of the Java
Community Process (JCP) orga-
nization. In this role, he oversees
the activities of the JCP’s Program

JAVA TECH
Management Office (PMO), including
evolving the process and the organi-
zation, managing its membership,
guiding Specification (Spec) Leads and
experts, chairing Executive Committee
meetings, and managing JCP.org.
Curran has worked in the software

ABOUT US
industry for more than 25 years.
His experience at Sun Microsystems,
and then Oracle, spans 20 years.
Before joining the JCP, he led the
Java Conformance Engineering
team in Sun’s Client Software
Group. He was also chair of Sun’s
Conformance Council, which was
responsible for defining Sun’s policies
JCP Executive Series and strategies around Java confor-

Charting the Future–JCP.next


mance and compatibility.
He has participated actively in
several consortia and communities
including the W3C (as a member of
Oracle’s Patrick Curran discusses the JCP’s evolutionary path the Quality Assurance Working Group blog
toward greater transparency and participation, and the embrace of and co-chair of the Quality Assurance
open source processes. BY STEVE MELOAN Interest Group) and OASIS (as co-
chair of the Test Assertions Guidelines
PHOTOGRAPHY BY BOB ADLER Technical Committee).
17
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
world where open source practices are
becoming increasingly ubiquitous. JSR
348 facilitates these practices.
JSR 355, also complete, was fairly

JAVA IN ACTION
simple. We previously had two sepa-
rate Executive Committees, one for Java
ME and one for Java SE/EE. Now those
have been merged into one. With Java
ME and Java SE/EE convergence on the
horizon, it no longer makes sense to
maintain two Executive Committees.
This change will streamline operations

JAVA TECH
considerably.
JSR 358 is still in progress. It will
take transparency and participation to
the next level, mandating the use of
open source development processes
and open source licenses for virtu-
ally all JSRs. This is a complex task,

ABOUT US
because it involves changes to the Java
Specification Participation Agreement
(JSPA), the legal contract that JCP mem-
bers sign when they join the organiza-
Curran (center) In this interview, Curran discusses ing behind closed doors for months or tion. It is difficult to modify the JSPA
confers with how the JSR process is being used even years, after which a new specifi- because it contains complex legal lan-
Thomas Lampart to modify itself toward greater cation would mysteriously appear. JSR guage dealing with issues such as intel-
of Gemalto M2M transparency, participation, and 348, which is now in effect, changes lectual property and licensing models.
(left) and Calinel
open source compatibility. that paradigm substantially. It requires We have to be very careful when chang-
Pasteanu of Oracle
at a JCP Executive Java Magazine: What are the most Expert Groups to conduct their busi- ing it, because the repercussions can
Committee meeting important changes implemented ness transparently via public mailing be far-reaching. So, JSR 358 is going to
prior to JavaOne. by JCP.next? lists and a public Issue Tracker. The JSR take some time. We’ve been working
Curran: JSRs 348, 355, and 358 are explicitly states that all JCP members, on it for a year, and it will probably take
collectively referred to as JCP.next. and members of the public, must have another year to complete.
These JSRs address a number of the opportunity to view, comment on, Java Magazine: The JSRs you described blog
important issues related to openness, and participate in the process. make great strides in transparency.
agility, and governance. Transparency and participation Where is there still room for improve-
There used to be a perception that are the keys to running an effective ment? And what roles will the Executive
Expert Groups operated secretly, work- standards-development process in a Committee and the PMO play?
18
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
Curran: All Expert Groups are comply- Java Magazine: In what ways will
ing with the “letter of the law.” Now JCP.next bring more individuals, Java
we must ensure that they comply with user groups [JUGs], and other entities
the “spirit.” There’s no point in having into JCP processes?

JAVA IN ACTION
a public mailing list if it receives little Curran: We expect that enabling
traffic, or if comments from outside people to participate through the use
the Expert Group are ignored. And of public mailing lists and open source
there’s little value in having a pub- development processes will make
lic Issue Tracker if very few issues are JCP participation much more attractive
logged, or if those that are logged are to the average Java developer. We’re
not acted upon. We must make sure actively recruiting JUGs through a
that people who wish to participate program we call Adopt-a-JSR, whereby

JAVA TECH
know how to participate, and that their developers get together through the
participation is effective. The JSR’s JUGs to assist with JSR efforts that
home page must provide the necessary interest them. This might involve
information to put all that in motion. activities such as critiquing the spec,
We’re working on a set of reporting testing the implementation, or being
requirements that will track the activi- involved with documentation. We now
ties of Expert Groups. They will have to have more than 40 JUGs as members, join the JCP is an active and vibrant Curran talks

ABOUT US
gather and publish this information, collectively representing tens of thou- JSR development process, the key to with Executive
and make it available for everyone. By sands of developers. In JSR 358, we’re greater involvement is to have a lot of Committee member
doing this, we believe engagement will working to create a new class of mem- JSRs in progress. This is not something Bruno Souza of
SouJava.
be significantly improved. bership tailored for individuals. This the Executive Committee or the PMO
Also, the PMO is working to provide will involve a membership agreement can directly influence, since JSRs are
information that will allow us to judge that is much simpler than the current initiated by our members. However,
how well an Expert Group is meeting complex legal document and will not we hope that the introduction of open
its transparency and par- require an employer’s source development processes and
ticipation obligations. OUT IN THE OPEN signature, which has open source licensing via JSR 358 will
We hope that the com-
bination of public dis-
“Transparency and sometimes been a stum-
bling block.
provide a significant boost in commer-
cial participation.
closure of information, participation are the
We’ve been very suc- Java Magazine: How will JCP.next use
public pressure, and the keys to running an
cessful in recruiting indi- both positive and negative reinforce-
Executive Committee
taking this information
effective standards-
viduals and JUGs, but
we still have work to do
ment to keep innovation on track?
Curran: We use a number of mecha- blog
into account when vot- development to increase participation nisms to encourage Spec Leads to
ing on JSRs, will motivate
the Expert Groups to fully
process.” by commercial entities.
Since the primary moti-
move their work through the process
in a timely manner. The main positive
meet their obligations. vation for companies to reinforcement is the Star Spec Lead
19
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
delay and convince the nance process be affected by JCP.next?
Executive Committee that Curran: Previously there was no formal
work is still constructively ballot before the Maintenance Release.
proceeding. There was nothing in the Process

JAVA IN ACTION
Java Magazine: What Document that required published
methodologies will JCP updates to the RI, the TCK, or even the
.next use to ensure that a Spec. Spec Leads would sometimes
specification, its Reference simply publish a change log and leave it
Implementation [RI], up to implementers to figure out what
and its Technology they needed to do to adopt the new
Compatibility Kit version. That didn’t make sense. Now
[TCK] are completed we have maintenance reviews similar

JAVA TECH
simultaneously? to the Final Review, whereby materi-
Curran: The PMO checks als are made available, the Executive
to be sure that the specifi- Committee will study them, and the
cation, RI, and TCK are all public will be granted access.
available before initiating But we’re aware that more work lies
a Final Approval Ballot. ahead. We expect to make further
The software licenses changes in JSR 358 in order to make

ABOUT US
are also required. If all the maintenance process more com-
these elements are not in patible with the type of continuous
place, the ballot cannot development and release processes
move ahead. We’ve also adopted by open source projects.
added some language to Java Magazine: Will you explore in
Left to right: Mike program, which publicly recognizes the Process Document stating that if greater detail the merging of the
Marzo of Goldman exceptional Spec Leads through the the materials are not formally posted Executive Committees for Java SE/EE
Sachs, Curran, annual JCP Awards. The awards also to jcp.org within 14 days, or if links and Java ME? How will this benefit both
and Jack Chung recognize outstanding JSRs and mem- to these materials are later broken, camps and the process as a whole?
of Aplix listen to a
presentation during bers who have contributed signifi- another Executive Committee bal- Curran: Java ME began as a subset
a JCP Executive cantly during the previous year. lot can be initiated to label the JSR as of Java SE, but over the years they’ve
Committee meeting. As for negative reinforcement, withdrawn on the grounds that the diverged. Now many of the new fea-
JSR 348 introduced the notion of time- Spec Lead has abandoned it. So we tures of Java SE, particularly the lan-
outs, whereby JSRs that do not reach hope this combination of checks will guage features, are being incorporated
defined process stages within specified ensure that all the necessary elements into Java ME, making them more simi- blog
time periods are subject to a Renewal are in place when the process is com- lar and compatible. So, the merging
Ballot. The Executive Committee may plete, and that they will continue to be of Executive Committees made sense,
then require that the JSR be withdrawn available to implementers. and was a simple change that we intro-
if the Spec Lead cannot justify the Java Magazine: How will the mainte- duced in JSR 355. We wanted to empha-
20
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
size that Java is one platform, and since balance of power between Oracle and by JCP.next. In conclusion, could you
we expect that Java SE/EE and Java ME others within the JCP? expand further on how JCP.next pro-
will become more aligned over time, Curran: This is one of the most funda- motes best practices?
it didn’t make sense to maintain two mental areas of concern as we revise Curran: Facilitating transparency and

JAVA IN ACTION
separate Executive Committees. The our processes via JCP.next. Obviously enabling participation are essential to
two committees seldom worked or Oracle has a special role as the stew- maintaining an effective standards-
met separately anyway. With the filing ard of Java, as the Spec Lead for the development organization in the
of JSR 360 (Connected Limited Device platforms, and as the most significant current era.
Configuration 8) and JSR 361 (Java ME investor in the development of Java People will participate only if our
Embedded Profile), the Java SE/EE/ME technologies. However, if Java were governance and processes are open.
convergence is in motion. We expect proprietary it would not have achieved That’s critical. These best practices
increased synergy between the Java SE/ such broad and ubiquitous success. increase the quality of the standards

JAVA TECH
Curran takes a walk EE and Java ME platforms and a more There are approximately 9 million Java we develop. With more active partici-
with Executive streamlined Executive Committee with developers worldwide. It is, therefore, pants, we’ll have greater diversity of
Committee member fewer members. critical that processes be open and viewpoints and more problems being
David Britto of TOTVS. Java Magazine: What is the current inclusive, and that others, particularly fixed. The resulting technologies ben-
Oracle’s competitors, have the oppor- efit across the board.
tunity to collaborate and to participate. JCP.next is a continuum that began
A significant majority of JSRs are with some basic transparency and

ABOUT US
now led by Oracle, which skews the participation changes, and is moving
Spec Lead role in Oracle’s favor. forward to embrace open source devel-
Others certainly participate, since opment processes and open source
they are active members of the Expert licensing. These modifications will help
Groups, but it would be healthier if to ensure the continuing strength and
there were more JSRs led from out- relevance of Java as we move forward
side Oracle. JSR 358 will embrace in a very dynamic and competitive
open source development processes landscape. </article>
and open source licensing, which we
hope will increase the participation Steve Meloan is a former C/UNIX soft-
of others in Oracle-led JSRs, and also ware developer who has covered the web
encourage the creation of more JSRs and the internet for such publications as
from outside the Oracle domain. It’s Wired, Rolling Stone, Playboy, SF Weekly,
a delicate balance between Oracle’s and the San Francisco Examiner.
legitimate business interests, as the blog
steward of Java, and the need for open
and collaborative processes. LEARN MORE
Java Magazine: Transparency and • Read Patrick Curran’s blog
participation are obviously enhanced • JCP.next
21
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
JAVA IN ACTION
JAVA TECH
ABOUT US
openHAB’s Kai Kreuzer (left)
and Thomas Eichstädt-Engelen
in front of the electrical cabinet
at Kreuzer’s home

SMARTEST HOUSE K
ai Kreuzer is not an easy man to
sneak up on. As you approach
the front door of his highly

ON THE STREET
automated house, you will trigger
a sensor that activates a webcam
mounted above the front door. Ring
the doorbell and he will be alerted to
The Internet of Things meets home automation with openHAB, your presence, via either loudspeak- blog
ers throughout the property or a video
a Java-based software environment that integrates devices and display on his iPhone. He may choose
applications into a cohesive network. BY DAVID BAUM to let you in by remotely unlatching
the door. With a few more taps on his
ART BY WES ROWELL; PHOTOGRAPHY BY TON HENDRIKS 22
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
Kreuzer controls his
home entertainment
system through
HABDroid, one of
the native clients

JAVA IN ACTION
for openHAB.

ing, transportation, and Bus (openHAB) in 2010, a Java-based


communications as bil- software environment that integrates
lions of intelligent devices devices and applications throughout

JAVA TECH
flood into our personal his home.
and professional lives. Java With openHAB as the controller,
plays a starring role as a all of a home’s comfort systems, secu-
central integration point in rity systems, and energy systems work
this machine-to-machine in concert and can be triggered in
world by making our cars unison—through a smartphone inter-
more efficient and depend- face, via Google Calendar events, or

ABOUT US
able, our homes more through many other hardware and
comfortable and secure, software interfaces.
SNAPSHOT phone he can adjust the lights, turn on and our healthcare less costly and Kreuzer’s brainchild quickly gained
the music, and adjust the temperature more patient friendly—to name a few traction in the open source commu-
openHAB
of the home’s central heating system. prominent examples. nity. Today there are 37 contributors
openhab.org
If he is in the garden, you may hear his Kreuzer studied mathemat- and between 2,000 and 3,000 open-
Headquarters: voice coming over a PA system, direct- ics and computer science at the HAB installations worldwide.
Darmstadt, Germany ing you outside. Technical University of Thomas Eichstädt-
Industry: What’s unique about this scenario is Darmstadt, where he COMMUNITY ROLE Engelen is a fellow
Home automation,
open source software
not the individual systems that auto-
mate every aspect of Kreuzer’s modern
took a particular inter-
est in Java. He has used Contributors help to home automation
enthusiast who now
Contributors:
37
home, but the way these systems work the language exten- expand the openHAB serves as a project

Java technology
together to improve the convenience,
security, and efficiency of dozens of
sively in his profes-
sional life as well as in
ecosystem by creating leader at openHAB.
With a degree in com-
used: routine tasks. his home automation connections to various puter science from the blog
Java SE 1.7 Home automation is a prime exam-
ple of the Internet of Things, a phe-
systems. This lifelong
hobby culminated with
devices, applications, University of Hagen and
full-time work in the IT
nomenon that is exploding across the the founding of open and interfaces. field, he is well versed
domains of healthcare, manufactur- Home Automation in the software industry
23
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
Kreuzer uses his
smartphone to
manually trigger his
sprinkler system.

JAVA IN ACTION
and has an affinity for the open source the heating system will shut off if the

JAVA TECH
movement. He joined Kreuzer a few windows are left open. The door won’t
months after the openHAB environ- lock behind you if you go out on the
ment was launched. balcony to get some fresh air.”
“My own home automation project
began with the physical infrastructure DESIGN GOALS: BETTING
and soon progressed to software,” ON JAVA AND OPEN SOURCE
Eichstädt-Engelen recalls. “It is not Kreuzer and Eichstädt-Engelen both

ABOUT US
enough to have the hardware in your have day jobs in the IT field and pur-
flat. You have to have something to sue openHAB in their spare time.
control it. I liked openHAB because it Eichstädt-Engelen is a software devel-
was free and open source. It was a per- oper at innoQ, a midsize software
fect fit to my skills because it is based consulting company. Kreuzer works at
on Java and OSGi.” Deutsche Telecom as an IT engineer
Eichstädt-Engelen has used open- and architect, with previous jobs in the
HAB at home to connect many dif- media and banking industries. “Java
ferent devices and applications into a was always my language of choice, per-
cohesive fabric. “In every room I have sonally and professionally,” he says.
a loudspeaker, centrally operated by In 2008 Kreuzer built a house
openHAB, along with the lights, the from scratch and decided to include
appliances, and the heating and venti- advanced automation systems that
lation systems,” he explains. “All of the could be interconnected. He worked
doors and windows have electric con- closely with an electrical engineer blog
tacts that signal the security system. to plan and wire the house. Like
Most of the electric appliances can be Eichstädt-Engelen, he was leery of
controlled remotely, and the various proprietary solutions that would tie his
systems work in unison. For example, automation systems to a vendor that
24
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
WORKING TOGETHER
OpenHAB enables discrete automation with centralized

JAVA IN ACTION
control: individual systems can be automated, yet each
one is aware of the others through a common controller.

might not exist in 10 or 20 years. a one-time or periodic basis. “Rather

JAVA TECH
“Since I planned to live in this home than giving a key to my cleaning ser-
indefinitely, I didn’t want to bet on a vice, I can issue an RFID tag. This lets
horse that wouldn’t win in the long me control when the lock will open for
run,” he says. “I knew that if I invested them,” he says.
in an open source solution I could A weather station in Kreuzer’s gar-
always extend it as technology evolved. den detects brightness, rain, wind,
It could be developed and maintained and temperature, along with moisture

ABOUT US
by myself and by others in the open sensors in the soil. Because the sprin-
Top: A weather station source community. As a professional kler system is attached to openHAB,
in Kreuzer’s garden Java developer, I was not really satisfied the watering system comes on only
detects brightness,
rain, wind, and with existing open source solutions so when the plants need it. A pump is
temperature, and I decided to create something com- activated with a float switch, which
sensors control window pletely from scratch and build it for also registers its activities, so there is
blinds, sprinklers, and my own use, yet make it flexible and always enough water in the tank for
the HVAC system. extensible so that it would also be the garden. This level of integration
Right: A GIRA system useful for others.” is what makes openHAB so useful in
monitors windows and Fast-forward five years and you can comparison to standalone or “siloed”
lights, shows missed
calls or visitors, and see the results of Kreuzer’s subur- automation solutions.
communicates via ban automation efforts. In addition “If you buy a security solution from
text-to-speech. to a webcam near the front door, he one vendor and a comfort solution
installed a Near Fields Communications from another, it is generally very
(NFC) reader that can control the lock difficult to combine them into one blog
based on signals from inexpensive RFID smart house,” Eichstädt-Engelen
tags that he issues to his guests. This explains. “In addition, many of today’s
method is particularly useful for service home automation systems were
people, who he may want to let in on designed for very high-end homes.
25
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
WORKING WITH THE job—or they can program openHAB
JAVA COMMUNITY so that the phone will signal these
The first binary build of openHAB was devices automatically whenever their
available for download in the fall of owner walks into the room.

JAVA IN ACTION
2010. Since then, Eichstädt-Engelen “Soon, presence detection technol-
and Kreuzer have presented the solu- ogy will allow openHAB to identify
tion at Java user groups and Java con- you as you move around the home,”
ferences such as EclipseCon, Devoxx, Kreuzer says. “This will allow open-
JAXconf, and GeeCON. Their growing HAB to adjust the lights or shutters or
community now includes a loyal base music to your preferences, based on
Kreuzer and Eichstädt-Engelen discuss of contributors that help to expand the the time of day or any other variables
openHAB with Java Magazine’s Caroline openHAB ecosystem by creating bind- you choose.”

JAVA TECH
Kvitka during JavaOne 2013. ings, or connections to various devices, End users simply download open-
applications, and interfaces. HAB and unpack it in a Java runtime
With openHAB, we are bringing this “Bindings are the pieces of code that environment on the target system.
same level of sophistication to average allow us to connect openHAB to other “It’s more or less a one-click instal-
homes and apartments.” systems and also to integrate it all lation,” Eichstädt-Engelen notes.
Home automation use cases can be together,” says Eichstädt-Engelen. “Within five minutes, you can have a
divided into three basic categories: There are currently about 50 bind- running openHAB system.”

ABOUT US
comfort, security, and energy manage- ings to commercial automation sys- The project includes the open-
ment. Some features of a home, such tems including Z-Wave, Plugwise, HAB Designer, an Eclipse Rich Client
as draperies and shutters, span mul- SONOS, Bluetooth, Modbus, EnOcean, Platform application for configuring
tiple categories: automatically opening and KNX. openHAB also provides con- the openHAB runtime. It comes with
them in the morning and closing them soles such as XMPP, OSGi, and Google editors for the openHAB configura-
in the evening keeps the house com- Calendar. Thanks to tion files, with full
fortable; saves energy; and improves these consoles and NO LOCK-IN integrated develop-
security, because it makes it appear as bindings, along with ment environment
if the resident is home even when the the steady evolution One of the fundamental (IDE) support such
house is empty. These activities can of home automation design goals is modularity: as syntax checking,
occur automatically based on the time
of day or can be triggered by sensors
technologies, home-
owners no longer need
it is easy to replace one autocompletion, high-
lighting, and content
that detect when people are home. physical buttons to technology with another assistance. Kreuzer
Lighting, heating, cooling systems, and
appliances can also be activated auto-
switch on lights and
other electric devices.
so that homeowners aren’t claims that this
mature development blog
matically or can trigger other systems. Pointing a smart- locked in to particular types environment makes it
For example, when Kreuzer’s washing phone at an NFC tag of applications and devices. easier to implement
machine finishes a load it broadcasts hidden behind the and deploy rules for
its status over the loudspeaker. wallpaper will do the automatic actions.
26
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
WHAT JAVA BRINGS
“Java is very useful because it has a huge
ecosystem of libraries, great debugging tools,
and lots of support available on the web.”

JAVA IN ACTION
—Kai Kreuzer, Founder, openHAB

JAVA TECH
openHAB also includes a scripting Using Java also makes
language so that developers can easily it easier to collaborate
define new types of automation logic. with other developers.
“OSGi is an important aspect for “There would be fewer
openHAB because it brings modularity contributors if we had

ABOUT US
to our systems,” Kreuzer explains. “This chosen another lan-
makes it easy for contributors to build guage,” Kreuzer adds.
modules and bindings independently “We are part of a big
of the core development. Users can ecosystem, so we can
pick relevant modules and add them to almost always find the
their openHAB system at runtime.“ solutions we need.”
“Java is very useful because it has Neither Eichstädt-Engelen nor closely aligned with Java. Kreuzer and Eichstädt-
a huge ecosystem of libraries, great Kreuzer plans to commercialize “Java is future proof and platform Engelen program
debugging tools, and lots of support openHAB. However, they recently pro- independent,” Kreuzer sums up. “The openHAB and test it
available on the web,” Kreuzer contin- posed the Eclipse SmartHome proj- Java APIs are very stable and consistent on a Raspberry Pi with
a tablet.
ues. “It’s easy to find a solution for a ect, which will make central parts of from one version to another. Java’s
specific problem. Java is also platform openHAB available under the Eclipse diversity makes it easy for other
independent, so you can run it on license. This move paves the way for contributors to get involved, all over
Linux, Windows, Mac, or an embed- the integration into commercial prod- the world.” </article>
ded platform.” ucts and ensures sustainability. blog
Eichstädt-Engelen agrees. “The But no matter where the openHAB Based in Santa Barbara, California,
best JVM [Java Virtual Machine] avail- technology goes and how the open David Baum writes about innovative
able for embedded systems is Oracle source community evolves, the two businesses, emerging technologies,
Java SE Embedded.” partners plan to keep the system and compelling lifestyles.
27
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
EST

AGILE ADJUSTMENT
NT

B
ME
LOP
E

S
V
DE

CE
P R A C TI

Java Champion Venkat Subramaniam explores the subtleties of agile development.

JAVA IN ACTION
BY TIMOTHY BENEKE

S
ince its inception in 2001, agile
development—defined on
Wikipedia as “a group of soft-
ware development methodologies
based on iterative and incremental
development, where requirements

JAVA TECH
and solutions evolve through col-
laboration between self-organizing,
cross-functional teams”—has had an
impressive history, with many orga-
nizations adapting its principles. In
recent years however, a number of
questions have arisen: What kinds

ABOUT US
of organizations make a good fit for
agile? Is it being deployed in dysfunc-
tional ways? Does agile development
require developers to have a certain
kind of skill set to be effective? What
goes wrong when agile fails?
To address these and other
issues, we met up with Dr. Venkat
Subramaniam, the founder of Agile
Developer, who has trained and men-
tored thousands of software devel-
opers in the US, Canada, Europe,
and Asia. Known for his contagious
enthusiasm, he helps developers
succeed with agile practices on their blog
software projects, and he speaks fre-
quently at international conferences
and user groups. He is the author
of many books, including, most
PHOTOGRAPHY BY BOB ADLER 28
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
ent part and draws a different conclu- Organizations have to be agile about
sion about it.  being agile. They have to try out a set
I recall a time when there was sus- of practices, but quickly make adjust-
picion about whether object-oriented ments to find out what actually works.

JAVA IN ACTION
development would ever work for the It is critical to apply practices that are
enterprise. Some companies suc- prudent based on the specific context
ceeded while others struggled as the of the organization, the team, and the
world ventured into the then-new environment in order to succeed with
paradigm. Today, it’s a foregone con- agile development.
clusion and object-oriented program- Java Magazine: To what degree are
ming is widely adopted. Organizations problems applying agile tied to the
are going through a similar phase with overall culture of companies?

JAVA TECH
agile, a learning curve, to figure out Subramaniam: Culture makes a big
what it is and how to use it. difference, but there is often not one,
Java Magazine: How are organizations company-wide culture in large organi-
using agile? zations. I’ve walked across a large floor
Subramaniam: I see two ways in which at a company and come across multiple
organizations have taken up agile. different cultures. 
There are organizations in which the Separate teams within the same

ABOUT US
Venkat Subramaniam recently, Functional Programming in management team has pushed agile, company might have different ways of
catches up on e-mail Java: Harnessing the Power of Java 8 and we see things such as Scrum responding to change, criticism, and
during a break between Lambda Expressions. being predominant. Then there are feedback. Some of them might be
sessions at JavaOne Prior to starting his own company, organizations in which the push is able to adapt to agile development
2013 in San Francisco,
California. Subramaniam worked in various posi- from the bottom up, and we see more- more easily than others.
tions, from programmer analyst to sys- technical or extreme pro- Java Magazine: Are there
tems architect, at organizations such as gramming practices being certain kinds of developers
AGILE’S ESSENCE
Halliburton, Raytheon, and Invensys. He predominant. Neither of who are not well suited to
holds a PhD in computer science from these situations is ideal, Collaboratively and agile development?
the University of Houston, where he is
an adjunct professor, and was named a
because there is a part
of the organization that
skillfully adjusting Subramaniam: Agile is
not well suited if the team
Java Champion in 2013. is not aligned with, sup- to feedback cycles would rather work in silos.
portive of, and responsive through iterative, The Dreyfus model of skills
Java Magazine: Why do people talk
about the demise of agile?
to the need for change.
The results of such efforts
incremental acquisition rates people
on a scale of one to five, blog
Subramaniam: It is a little like the par- are often not very positive development is the with five being people who
able of the four blind men who visit an
elephant at the zoo. They cannot see
unless the rest of the orga-
nization joins the effort to
essence of agile. glow in the dark—these
are folks who get things
the elephant, so each touches a differ- foster change. done with no guidance or
29
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
Ego is like cholesterol—there are good any better. A quick check on our atti-
The Agile In February 2001, 17 developers gathered at a resort
in Utah to explore how best to produce software. parts and bad parts. We all want to take tudes and levels of trust is the first step.
Manifesto The result, the “Manifesto for Agile Software pride in our individual work, while at
the same time, we have to place the
Given all things equal, I do believe that
face-to-face conversation brings better
Development,” stated, in its entirety:

JAVA IN ACTION
“We are uncovering better ways of developing software by doing it success of the team ahead of that. It results. But all things are rarely equal.
and helping others do it. Through this work we have come to value: comes down to openness and accept- Java Magazine: Your most recent book,
ing trade-offs. The agile methods work Functional Programming in Java:
Individuals and interactions over processes and tools better in teams in which developers put Harnessing the Power of Java 8 Lambda
Working software over comprehensive documentation forth their ideas, not as a fort to defend, Expressions (Pragmatic Programmers,
Customer collaboration over contract negotiation but as something that should evolve 2013), points to a different way of doing
Responding to change over following a plan and be improved upon by their team. Java programming. How might this
Java Magazine: One of the original relate to agile development? 

JAVA TECH
That is, while there is value in the items on the right, we value the
items on the left more.” principles of agile emphasized that Subramaniam: Lambda expressions
In addition, they offered 12 basic agile principles that ranged from face-to-face conversation is the best in Java 8 open up the possibility of
the importance of change and of working software, to the value of sim- form of communication. This method functional programming in Java. This
plicity, sustainable development, and face-to-face communication. emphasizes both personal interaction style of programming, if done well, can
and conversation, which implies rela- lead to fewer errors, more-elegant and
tionships of relative equality. more-concise code, and code that is
Subramaniam: Yes, it does. I have had far easier to parallelize. Fewer moving

ABOUT US
many very productive relationships parts in functional-style code means
intervention. One consists of novices; working with people who I have never it’s easier to write automated tests and
leave them alone with a task and they met in person, or only met years later, easier to evolve the highly expressive
might struggle to get moving. Each of so face-to-face conversations are by code. This can lead to code that’s ready
us varies on this scale for various activi- no means absolutely necessary for for feedback more rapidly than in the
ties we perform. So there is no level- good communication. It is a matter of past. Agile development, in essence,
one person or level-five person—we’re the attitudes that people bring to the is feedback-driven development.
at various levels for different activities. interaction. Two people, no matter how Collaboratively and skillfully adjust-
The study says the average level in any far away they are, will produce bet- ing to feedback cycles through itera-
organization is level two, which is not ter results if they’re keen on working tive, incremental development is the
sufficient for excelling. We can raise together and value the collective suc- essence of agile. </article>
this level for a team through active col- cess. More than on face-to-face com-
laboration and open communication. munication, we need to focus on the
Some developers are naturally open trust we have built. Timothy Beneke is a freelance writer
to communication and constructive If I whine and complain about some- and editor, best known for his books blog
criticism. Some developers simply are one to you, you’re going to wonder on gender.
not, and that can be a problem. There’s what I say about you to others. This
a cautious balance we have to strike erodes trust. Having a face-to-face LEARN MORE
between personal pride and team spirit. conversation is not going to make this • Venkat Subramaniam’s blog
30
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java architect /

COMMUNITY
EST
NT

B
ME
LOP
E

S
V
DE

CE
P R A C TI

Diabolical Java Performance Tuning

JAVA IN ACTION
Lessons in what not to do.

I n this article, we’ll discuss


how to approach perfor-
mance tuning and wrestle
cation performance (even
Wikipedia agrees).
Microbench­marks are the
tant part of modern software
development. In a perfor-
mance context, it means
work of a performance
engineer—squeezing every
last glistening drop of perfor-
with the #1 problem that all best type of benchmark. that you should never run mance out of the algorithms

JAVA TECH
applications need to be con- They’re fun to do, and once any performance test more in your application.
cerned with. you understand the low-level than once. With so many Measuring things is for
Never mind about reliabil- detail of your application’s other development tasks, it’s people who don’t have your
ity, supportability, elegance, behavior, it’s easy to just important not to waste time keen insights; you built the
BEN EVANS AND architectural flexibility, ease extrapolate up from that and on the dull work of repeating app, so you know exactly
MARTIJN VERBURG of understanding, or even deduce how the rest of the a performance test. After all, where the problems are.
correctness. All that matters stack will behave. you’re a perfectly compe- Algorithm optimization is

ABOUT US
is getting a result out quickly. The best kind of micro- tent professional, so you’re hard, so that’s where the real
Who cares if you’re right benchmark is where you bound to have set up the test performance professionals
BIO
tomorrow? All that matters is can prove that some very perfectly and gotten all the spend their time; never mind
getting the result (any result) low-level aspect of the Java bugs out of the run the first collecting and analyzing data.
as quickly as possible—if Virtual Machine (JVM) has time around.
you’re faster than everyone some tiny performance Ignore anyone who says Optimizing Algorithms
else, you can define what’s differences—these types things such as “statistical The bottleneck is almost cer-
“right.” Smart developers of results are always sig- significance” or “shape of the tainly where you think it is.
focus on performance to the nificant when aggregated distribution.” They’re proba- Trust in your amazing analyt-
exclusion of all else. up into a whole system. For bly just math nerds who can’t ical skills—they will lead you
example, it stands to reason cope with the awesomeness to the right culprit, which is
Using Benchmarks that dispatch of an interface required to be a real perfor- usually any code that wasn’t
Always believe the bench- method absolutely must be mance rock star ninja. Do the written by you.
marks you find online—what slower than regular virtual test once and just measure Fortunately, optimiza-
could go wrong? Following dispatch, right? the averages (and by aver- tions of other people’s code blog
that, it’s also important to ages, we mean the mean), are easy to do. First, find any
understand that bench- Handling Data and Results and you’ll be done handling code with a simple, unop-
marks always correlate really The Don’t Repeat Yourself those annoying results. Then timized algorithm. A good
PHOTOGRAPHS BY
JOHN BLYTHE AND BOB ADLER well with real-world appli- (DRY) principle is an impor- you can get back to the real candidate is anything that
31
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//java architect /

COMMUNITY
has a long-running loop with a Don’t worry that some of the results carefully. Otherwise, some always remember to scrutinize the
conditional check in the middle of switches seem to do conflicting or other people might steal your newest technology very closely.
it. Now, remember that general- contradictory things. A true profes- work and claim credit for it. Never If you don’t fully understand
case algorithms are stupid. You sional (such as you) will also use let them independently recheck it (bearing in mind that you’re

JAVA IN ACTION
understand your data set better the undocumented ones found in your work. They’ll just get it wrong a genius), there’s bound to be
than anyone else, so you should the Java HotSpot VM source code. and detract from your obviously something not quite right about it.
spend as much time as you need correct conclusions.
to design a specialized algorithm Understanding the Hardware Better yet, let others do the Conclusion
that fits your data. Someone of Understanding the CPU is a waste boring work for you. If someone Performance tuning can be boiled
your talent and intellect can surely of time—it’s the kind of thing that else has already done something down to a few very simple rules:
do better than mediocre, compro- is best left to hardware engineers. vaguely similar and written it up ■■ Performance is the most impor-

mised textbook examples. A software engineering genius on a blog or the Stack Overflow tant aspect of any application.

JAVA TECH
Don’t worry if this takes quite a shouldn’t have to care about L3 site (especially if they have a high ■■ You are awesome, which is why

lot of time; this is the most impor- caches or how the data is actually reputation score), just accept their you’re doing the tuning—it’s
tant part of performance tuning, laid out in memory. conclusions—that’s close enough. the most important job of all.
and doing it correctly is likely to Solid-state drives are faster in all After all, how different can the ■■ Performance analysis is all

require someone of your abilities. use cases, so use them all the time. behavior of two applications be? about staring at source code
Don’t bother to measure the actual It’s all just Java (or all just the and optimizing algorithms.
Optimizing the JVM throughput or other observables. JVM), right? ■■ Other people will likely mess up

ABOUT US
Don’t bother testing with recent Remember, more capacity is bet- Once you’ve reached your con- your good work, so guard it from
releases of Java and tracking the ter, so buy loads of RAM and really clusions about how to improve them jealously.
minor version numbers. Nothing push up the size of your heap. performance, whether that ■■ Measuring is boring and

much changes internally between involves using an optimized algo- unnecessary.


major releases of Java. Using Performance Advice rithm or a new bit of ultrafast shiny If you follow these basic rules,
Instead, you can often get better Performance advice is like fine tech, it’s a better use of your time your application will be on the
performance by fiddling with the wine: it just gets better with age, to browbeat your colleagues into front page of major industry publi-
switches you pass to Java. Don’t and it certainly never goes out of accepting your solution than to cations in record time.
bother being systematic about date. Performance advice from waste time having them indepen- Needless to say, the diabolical
this—just locate a set of switches the 1990s is still absolutely accu- dently check your conclusions. advice in this article should not
that you think have some bearing rate today. You should build on Always show them who’s boss, and be followed, but instead should
on the problem, and play around the deep insights of the amazingly never document or explain your be referenced as an anti-patterns
with them until you find a combi- smart engineers who came up reasoning—the last thing you want guide. </article>
nation that works for you and will with the tips in the first place. They is to have them messing around
give you extra, free performance were probably a lot like you. with your carefully tuned system. blog
with no downsides. LEARN MORE
There are more than 100 per- Working with the Team Scrutinizing Technology • “Java Performance Tuning”
formance tuning switches for the Always remember to guard your When thinking about the appli- • “Nine Fallacies of Java
JVM. Use as many as you can. performance test harnesses and cation architecture as a whole, Performance”
32
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
JAVA

JAVA IN ACTION
CONCURRENT
ANIMATED

JAVA TECH
Java Champion Victor Grazi on writing better
concurrency applications BY JANICE J. HEISS

ABOUT US
In 2009, Java Java Magazine: How many peo-
EST
NT developer Victor ple have now tried out your Java
B

PME
LO Grazi introduced Concurrent Animated app?
VE
S

E
D Java Concurrent Grazi: The app was introduced in
CE

P R A C TI
Animated, a much- July 2009; since then, we’ve had
praised set of animations that about 20,000 downloads. Given
serves as a tutorial for concurrency that there are perhaps 10 million
development. Recently inducted Java developers out there, we are
as a Java Champion for his con- only scratching the surface. Top
tributions to the Java commu- downloads by country are the US
nity, Grazi is a vice president at (23 percent), India (14 percent),
JP Morgan Chase’s Securities and China (7 percent).
Lending division. He is a frequent You can download the self- blog
presenter at technical confer- executing JAR file. Then just
ences where he speaks about his double-click the JAR file to start
first love, Java concurrency, and it. It is menu-driven, or you can
other Java-related topics. use the up and down arrow keys
PHOTOGRAPHY BY CHRISTOPHER LANE/GETTY IMAGES
33
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
MORE THAN IT SEEMS
to navigate between
the various image and
Java Concurrent efficiencies, and sud-
denly code that has
Suppose a writer is waiting for some
working readers to release the read
animation slides. It Animated is not just been working like a lock, and suddenly a new reader comes
works on all platforms— some Flash animations; charm will start experi- along. Who should get preference?

JAVA IN ACTION
Windows, Mac, Linux, encing sporadic failures Should the reader move ahead of the
and so on. Java SE 6 or it is a set of interactive due to incorrect concur- writers—after all, why have a new reader
higher is now required. Java programs, such that rency management. wait around for a waiting writer if other
Java Magazine: What
are the typical each animation is actually Java Magazine: Would
you say that your app
readers are already holding the lock?
So that was how it worked in Java 5. But
responses to it? utilizing the underlying does some of our imag- once I started running the animation in
Grazi: People tell me
that they find it very
concurrency component ining for us in ways that
enable developers to
Java 6, I noticed the behavior changed,
and subsequent readers would wait for
it is illustrating.

JAVA TECH
helpful. Many really get intuitively grasp Java con- all waiting writers to release the lock
excited about it, espe- currency principles and before acquiring the lock.
cially teachers and team processes more quickly?
leads who are trying to Grazi: That’s an inter-
impart proper concurrency skills to esting way to put it. You see, Java Available Animations
teams. Java was one of the first lan- Concurrent Animated is not just some
Available Java Concurrent Animated
guages to introduce concurrency into Flash animations—it is a set of inter-

ABOUT US
animations include Executors
its core library. It was a powerful fea- active Java programs, such that each
[FixedThreadPoolExecutor,
ture, but we suddenly found some very animation is actually utilizing the
SingleThreadExecutor,
good programmers writing some very underlying concurrency component it
CachedThreadPoolExector, and
bad code. Proper concurrent program- is illustrating. There is a snippet panel
RejectedExecutionHandler(s)];
ming is difficult to impossible to get on the right side of the screen, and as
Future; synchronized;
right, but if people would take the time an animation proceeds, executing code
ReentrantLock; Condition;
to understand some of the frameworks snippets are dynamically highlighted
Semaphore; ReadWriteLock;
out there, it would make coding for and restored as they execute.
CountDownLatch; CyclicBarrier;
concurrency much less error prone. Let me give you an example that
Phaser; AtomicInteger;
Take, for example, the Java memory happened with the ReadWriteLock
BlockingQueue; TransferQueue;
model. Developers often ignore it animation. A ReadWriteLock is used to
CompletionService;
and code away blissfully ignorant ensure data consistency. It allows an
ConcurrentHashMap; and
that their code is broken, because the unlimited number of reader threads
ForkJoinPool.
Java Virtual Machine (JVM) and serv- to acquire a read lock and operate
In addition, Grazi has an animation blog
ers might not leverage the optimiza- concurrently. But a writer thread must
for the Java memory model and new
tions provided by the Java memory wait for all readers to complete before
Java 8 constructs in the works.
model. But as cores increase in speed it can acquire the lock. Once a writer
and number, manufacturers are thread acquires the lock, no other
expected to take advantage of these reader or writer can acquire it.
34
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
is difficult to come back later and try
to reconstruct our prior thought pro-
cesses. Certainly, if a different devel-
oper dives in later, it is that much

JAVA IN ACTION
harder to recapture the cognitive cir-
cuits from the original effort. So, sud-
denly, brittle code starts breaking.
By using a framework, we are not
only delegating the concurrency
to the smart people who built and
maintain the framework, but we are
also employing a lexicon for com-

JAVA TECH
municating our design. So, I can say,
“The following code is operating as a
CyclicBarrier,” and people will under-
stand what that means. By introducing
interactive animations for all the
java.util.concurrent components, devel-
opers can click buttons to easily visual-

ABOUT US
ize the functionality they are exploring,
making it much easier to viscerally
assimilate the algorithms.
Java Magazine: You were operating on
some intuitions about what would
Figure 1 make it easier to learn concurrent
programming—intuitions that appear
I thought this new behavior was their behavior depending on the JVM to be valid, judging from the response
a bug and mentioned it to concur- runtime version. of developers. Can you make those
rency expert Dr. Heinz Kabutz, who Java Magazine: What is distinctive intuitions explicit?
explained that it was not a bug but a about Java concurrency programming Grazi: Well, yes. For example, above
feature. If new readers were allowed that makes an animated tutorial of I explained the basic workings of a
to jump ahead of waiting writers, particular value? ReadWriteLock. Readers might have
there is a high risk of producing a Grazi: Miller’s Law teaches that there understood it or not. Now take a look
thread-starvation condition because is a limit to the number of concepts at the animation for that, which is blog
there is a high probability that no our brains can hold at one time. The shown in Figure 1.
writers would ever get in, and they human brain tends to process sequen- The green threads are the read-
would accumulate forever. That’s an tially, so even if we overcome our physi- ers, the top white thread (with the
example of how the animations alter cal limitations and get things right, it diamond-head) is a writer, and the
35
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
were managing a development team
that was using Java concurrency and
you wanted to understand it better and
have your team understand it better.

JAVA IN ACTION
Can you describe the process by which
this led you to the animations?
Grazi: My training is in server-side
Java at investment institutions, where
concurrency is a common concern.
Traders require low latency to ensure
that they won’t lose to a competitor in
a 1 millisecond window of opportunity

JAVA TECH
for grabbing a trade. Batches need
to be completed quickly, and so on.
So I started seeing horrific write-only
constructs that confirmed that people
were struggling with concurrency. I
have been there myself.
One afternoon, while I was sitting in

ABOUT US
an airport heading to Chicago to make a
concurrency presentation for my team,
I was putting the finishing touches on
a PowerPoint presentation that had a
sequence of slides dedicated to each of
Figure 2 the important constructs. I had written
a little functioning state machine that
white thread beneath it is a new reader, skills of programmers so that they have displayed simple text messages that
which must wait for the readers and less risk of concurrency bugs? I would refer to in order to guide me
writer to finish before acquiring the Grazi: Very often when I am grap- through the important states of each
lock. If you click buttons and see the pling with a concurrency problem, I concurrency construct in java.util
animations, it becomes much easier to know that the solution lies in some .concurrent. In a previous lifetime, I had
understand than parsing through some design pattern, but which one? Java worked at an interactive gaming dot-
turgid explanation. Concurrent Animated provides a cata- com startup, so I knew a lot about ani-
Java Magazine: Heinz Kabutz has log for developers in their quest for the mation. It occurred to me that I could blog
remarked that Java was built to be right concurrency solution; it acts as a replace the PowerPoint slides with a
able to do many things at once, which muse that inspires the correct solution. series of interactive animations that
is what concurrency is all about. How Java Magazine: Java Concurrent would be much more intuitive.
does your learning system improve the Animated had its origins when you I worked on an initial animation
36
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
Zeigermann pointed out that an ani-
mation for ConcurrentHashMap was
conspicuously absent. I asked him if he
would be interested in contributing it

JAVA IN ACTION
and he made that valuable addition.
Java Magazine: Could you take us
through some of the classes of Java
concurrency and explain how anima-
tion makes it easier for developers to
get insight into each one?
Grazi: Well, it would be difficult to do
that without an animation, but let’s

JAVA TECH
take a look at the CyclicBarrier, which
has two important states, as shown in
Figure 2 and Figure 3, which illustrate
a barrier with four parties. In Figure 2,
we can see that only three parties
have arrived, so they are prevented
from proceeding. Figure 3 shows that

ABOUT US
once the fourth party arrives, every-
one moves forward.
So this illustrates the barrier con-
cept, which is that each party must
wait until all parties have arrived. As
Figure 3 the constructs increase in complexity—
for example, the fork/join animation
engine while waiting for that flight, adding some true PowerPoint expla- or the animation demonstrating the
and then I hooked in my state nations to the animations so that native wait and notify mechanism—the
machine. By morning I had a func- presenters have a trigger to remem- benefits are more pronounced.
tioning prototype. Over the years, I ber what to discuss. I added that, and Java Magazine: Tell us about some of
have tightened the framework, incor- it is a very helpful feature—not just the challenges you have faced in creat-
porating suggestions from experts. I for presenters but even for end users. ing the animations.
sent an early version to Brian Goetz Heinz Kabutz also joined the presen- Grazi: There have been several.
and was surprised to receive sug- tation and suggested some changes Originally, the animations represented blog
gestions for each animation. I incor- to the original animations that would threads as arrows, which worked for
porated all of his suggestions. Kirk make them more intuitive. most of the components. But then we
Pepperdine joined me at my first pre- At another presentation, a passion- had to provide a visualization not for
sentation at JavaOne and suggested ate software consultant named Oliver threads but for objects being queued
37
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
COMMUNITY
ized, because each value depends on
the prior values. Therefore, it is inher-
ently a sequential calculation no mat-
ter how you try to parallelize it. So, I

JAVA IN ACTION
switched to a different problem—that
of finding the greatest element in an
array, which worked nicely. During
the animation, you can see the actual
problem being solved using random
array values (see Figure 4).
Java Magazine: Where has your anima-
tion been presented?

JAVA TECH
Grazi: I presented it at JavaOne a
few times and also at many other
conferences—such as JavaZone in
Oslo, Jazoon in Zurich, QCon in New
York—and at many SIGs [special
interest groups] and JUGs [Java user
groups]. I love presenting and I love

ABOUT US
traveling around the world, so Java
Concurrent Animated has provided
me with a great opportunity to do
both. It always gets high ratings.
The Java Concurrent Animated pre-
Figure 4 sentations provide awareness, and
they also show the attending develop-
in a BlockingQueue. So, I had to intro- existing framework. There was an ers the value of downloading the app
duce a concept of “sprite-type,” and additional challenge there. The fork/ and how much easier learning concur-
then we had an arrow sprite-type and join animation needed to solve a real rency can be if you have a framework
a new “object” sprite-type that is ren- problem, but which problem should and an inspiration. </article>
dered as an oval, not an arrow. Then the animation solve?
ConcurrentHashMap and AtomicInteger I originally had the animations solve
Janice J. Heiss is the Java acquisitions
required a new sprite-type, because for the nth Fibonacci number, but
editor for Java Magazine and Oracle blog
we are trying to visualize their compare that was not working. I wrestled with
Technology Network.
and swap activities. that for a couple of days until I real-
Then fork/join came, and the chal- ized that the recursive definition of
lenge was how to represent some- the Fibonacci sequence (Fn+1 = Fn + LEARN MORE
thing completely different using the Fn-1) cannot be efficiently parallel- • Java Concurrent Animated
38
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
EST
NT

B
ME
LOP
E

S
V
DE

CE
P R A C TI

Database DevOps with MySQL,


Hudson, Gradle, Maven, and Git

JAVA IN ACTION
DevOps will help developers produce higher-quality software.
MICHAEL HÜTTERMANN

T he term DevOps Different processes and

JAVA TECH
■■

BIO describes the improved concepts: For develop-


collaboration between ers, more-pragmatic
development and opera- approaches; for opera-
tions teams. In software tions staff, more focus on
engineering, databases are reproducibility
often on a critical path. This ■■ Different tools: For devel-

article describes DevOps opers, development

ABOUT US
and explains what database tools; for operations staff,
DevOps might look like using more production-like
concrete concepts and tools. approaches
So first, let’s start with These differences often
conflicts that occur during lead to gaps or silos between
software engineering. departments, which I’ll
cover next.
Conflicts Due to Different Figure 1
Goals, Processes, and Tools Different Teams
Often conflicts exist between In traditional settings, the finished their work. production infrastructure
development and operations term development describes The term operations refers (for example, setting up and
teams, primarily for the fol- mainly the programmers to a team that comprises maintaining the servers and
lowing reasons: on the development team database administrators, systems). The operations
■■ Different goals: For devel- (see Figure 1). Testers and system administrators, group essentially accompa-
opers, more changes in a QA personnel are also part network administrators, and nies and accounts for the blog
short time; for operations of the team, but they often other types of administra- “last mile” in the delivery
staff, fewer changes in pro- have dedicated project roles, tors. These are the experts process.
duction and, thus, more and their activities start after who put the software into In a barrier-rich setting,
stability the programmers have production and manage the both groups form silos, in
40
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
which they have locally optimized other hand, is often based on a duce higher-quality software that essential for DevOps to gain
goals and their own processes central resource. In many cases, is more aligned with individual quick feedback.
and tools. though, local developer databases requirements and basic conditions. ■■ Measurement. DevOps finds a

Developing software is hard; or individual schemas in central DevOps seeks to align goals, specific path to measurement.

JAVA IN ACTION
developing databases is harder. databases are used to provide concepts, and tools with each Quality and shared (or at least
isolated and productive working other for both development and aligned) incentives are critical.
Database on the Critical Path environments. operations. DevOps is about ■■ Sharing. Sharing creates a

Let me give some concrete exam- In addition, database deploy- improving the collaboration of collaboration platform for
ples of what daily struggles might ment is not a straightforward pro- development and operations (the exchanging ideas, knowledge,
look like for database develop- cess of copying and replacing. For why) through shared goals, con- and experience.
ment. Application developers example, a database table cannot cepts, and tools (the how). In defining and rolling out data-
apply continuous integration, be simply dropped and afterward With DevOps, organizational base DevOps, it can be helpful to

JAVA TECH
including frequent check-ins and recreated with the new structure. barriers are minimized. With the distinguish among four different
automated testing, and they often With database deployments, often “one team approach,” the usage areas. Figure 2 shows the DevOps
apply continuous deployment of no two deployments are exactly of agile practices is expanded to area matrix approach. Area 1 is
the business application to the the same, since either the source operations. Experts from develop- about extending development to
target environment. Database or the target has been altered or ment and operations are both now operations. A common use case
developers, on the other hand, updated by previous deployments “developers,” meaning that they for this, in a database context, is
often lack the basics for real data- or new developments. work together closely and help to to put conversion scripts into the

ABOUT US
base version control and continu- DevOps can help to streamline “develop” the solution. version control sys-
ous deployment. software development, including DevOps targets dif- WHY THE CONFLICT? tem and use the same
This gap is created by the major
differences between application
managing changes on databases,
in a holistic way, spanning differ-
ferent activities and
aspects.
Often conflicts database migration
tool in development
development/deployment and ent departments. Now let’s exam- exist between and operations, such
database development/deploy-
ment. Traditionally, application
ine in more detail what DevOps is
all about.
Numerous Activities
and Aspects
development as Flyway, which we’ll
discuss a bit later.
development is based on local DevOps encompasses and operations Area 2 is about
files, with local changes being DevOps in a Nutshell numerous activities teams—primarily extending operations
published only upon check-
in. Developers can change and
DevOps describes practices that
streamline the software delivery
and aspects, such as
the following:
due to different goals, to development. For
database DevOps,
debug code locally, without process, emphasizing learning by ■■ Culture. This con- different processes, this means providing
interfering with the work being
done by other team members.
streaming feedback from produc-
tion to development and improv-
cept emphasizes
people over pro-
and different tools— visibility for traffic on
production systems,
Deployment is performed by ing the cycle time (that is, the cesses and tools. which lead to gaps including locked rows, blog
automatically copying deliver- time from inception to delivery). Software is made by or silos between blocking queries, and
ables from the build server to
respective environments.
DevOps will not only empower you
to deliver software more quickly,
and for people.
■■ Automation.
departments. resource contention.
Area 3 embeds
Database development, on the but it will also help you to pro- Automation is development into
41
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
operations. Examples include most effective way to overcome
setting up constraints and shared daily challenges. With features
goals for nonfunctional require- such as version control, continu-
ments. Examples of shared goals ous integration, and automation,

JAVA IN ACTION
are that 80 percent of database database change management
searches will return results to the enables DBAs and developers to
screen in less than two seconds better communicate and collabo-
(a shared performance goal); rate with each other and to avoid
the system shall not make use of the potential pitfalls—accidental
any technology that would make overrides, conflicts, and so on—
it difficult to port to that can arise when they
another Linux distribu- work in silos. That, in

JAVA TECH
WHY SILOS?
tion (a shared portabil- turn, will lead to greater
ity goal); the database In a barrier-
returns from DevOps Figure 2
will be capable of stor- rich setting,
strategies. The following
ing 20 million members
on the specified hard- both groups
patterns might help to
foster DevOps, particu-
Contraction scripts migrate the
database and break backward
items to a defined baseline.
Automatically deploying data-
ware while still meeting form silos, in
larly database DevOps. compatibility (for example, remov- base changes results in the need
performance objectives
which they have
Use database update ing structure). for a process that supports apply-

ABOUT US
(a shared capacity goal); scripts. With DevOps, Using expansion and contraction ing database changes incremen-
or automated tests locally optimized
database elements scripts conveniently decouples tally while preserving current
must exist for all com-
ponents including infra-
goals and their
should be released auto-
matically, with update
database migrations from applica-
tion deployments.
structure and content. Many
approaches exist for updating an
structure code (a shared own processes
scripts. It is a good idea Release databases automatically. existing database, and all have the
maintainability goal). and tools.
to distinguish update One of the more-advanced chal- following activities in common:
Area 4 embeds opera- scripts between data- lenges in automatically releasing ■■ Put all code and database ele-

tions into development. base expansion scripts databases is to link the database ments (all change sets) into ver-
This can be done to and contraction scripts. in its current version (that is, the sion control.
enhance collaboration by pro- Expansion scripts involve data- current set of structural elements, ■■ Create SQL scripts that have to

viding access to information to base changes that can be applied such as tables and columns, and be applied to roll forward to the
development without the involve- without breaking the database’s their data)—or, in other words, in next version and to roll back-
ment of database administrators backward compatibility with the its current state—with the current ward to the previous version of
(DBAs), thus preventing DBAs existing version of the application version of the rest of what makes the database. These scripts are
from being gatekeepers. (for example, adding elements, up the complete release. By grouped into single change sets. blog
such as new tables or columns). having database elements already ■■ Investigate whether a roll back-

Database DevOps These scripts can run at any point under version control, you can ward mechanism is needed at
A robust database change- before upgrading the correspond- create tags (often called labels) all. Increased complexity can
management solution is the ing application. and add all of your configuration be avoided by accelerating the
42
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
development flow and is a good cated working directory. SQL; thus, it’s a good AVOIDING CONFLICT in, Gradle, or Ant. It
strategy for applying hot fixes. Store the database version. One discussion base for can also be executed
With features
■■

■■ Create one file for each change approach is to use a database both development from the command
set to hold the respective change table that holds the meta- and operations, as such as database line. Now let’s focus

JAVA IN ACTION
set. Give the file a unique name
including a numbering scheme.
information, especially the ver-
sion of the database scheme.
well as being a solu-
tion that is light and
version control, on the Flyway support
for MySQL.
Change sets move the database Additionally, you can create col- straightforward. continuous Flyway and MySQL.
forward (or backward). Change
sets are applied based on a
umns for SQL scripts that have
to be applied to roll forward and
Flyway only has a
few dependencies;
integration, and Flyway supports the
standard SQL syn-
baseline. Thus, the concrete to roll backward. Shell scripts you need Java 5 or automation, tax with statement
content of a change set might can now roll backward or for- higher and a JDBC database change delimiters, including
contradict a previous change ward using the information held driver. It applies the
management enables delimiter changes for

JAVA TECH
set. In other words, each change in the database. pattern of convention stored procedures
set can consist of multiple SQL ■■ Consider monitoring to mini- over configuration, for DBAs and developers using DELIMITER
statements. For managing one
specific change set, favor one
mize mean time to repair
(MTTR), mean time to detect
example, to automat-
ically discover SQL
to better communicate statements. You can
use comment direc-
file over multiple files, to foster (MTTD), and smoke testing. migrations through and collaborate with tives generated by
task-based development. You can develop a solution your- classpath scanning. each other and to avoid mysqldump (/!.../;)
Create baselines in which self, or you can use a framework It supports many
the potential pitfalls— and MySQL-style

ABOUT US
■■

you freeze all the configura- such as Flyway. In the upcom- databases, includ- single-line comments
tion items of your applica- ing sections, we’ll go through an ing Oracle Database accidental overrides, (# Comment).
tion, including the database
elements.
example of using Flyway in an
integrative build chain, integrating
10g and higher (all
editions, including
conflicts, and so on— DDL exported by
mysqldump can be
■■ Retrieve the baseline for deploy- Maven, Gradle, Git, and Hudson. Oracle Database, that can arise when used unchanged
ment. In cases of a full installa-
tion, apply again the initial base- Flyway, the Database
Express Edition) and
MySQL 5.1 and higher.
they work in silos. in a Flyway migra-
tion. Any MySQL SQL
line of database elements and Migration Tool Data definition lan- script executed by
the sum of incremental change Flyway is a database migration tool guage (DDL) files Flyway can be exe-
sets. In cases of incremental that supports the concepts men- exported by Oracle cuted by the MySQL
installation, check the current tioned earlier. It can be used by Database or MySQL can be used command-line tool and other
state (the version) of the spe- both development and operations. unchanged in a Flyway migration. MySQL-compatible tools (after any
cific database and apply all new Actually, development has to write Any Oracle Database and MySQL placeholders have been replaced,
change sets (that have not been the change sets and has to test script executed by Flyway can be which allow parameterized calls
applied before) to it. the deployment on test machines. executed by SQL*Plus and other and configuration). blog
■■ Ensure that the deployment Flyway can migrate from any ver- Oracle-compatible tools (after the
process picks up a baseline from sion (including an empty data- placeholders have been replaced). A Concrete Example
version control. Place the data- base) to the latest version of the Flyway can be executed in many Now for an example. Let’s start
base change sets into the dedi- schema. It’s based on plain old ways, including via a Maven plug- by looking at the folder where the
43
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5
migration scripts are located. They in mind that Flyway uses classpath
are placed in the resources folder scanning: the migration scripts michael@michael-VirtualBox:~/talk/project/devops/src/main/re-
sources/db/migration$
in our project source tree (see must be copied to the target (that
ls -la
Listing 1). is, Maven’s target folder) to be
total 16

JAVA IN ACTION
At the moment, we have two applied successfully. The Maven drwxrwxr-x 2 michael michael 4096 Sep 22 11:16 .
files of plain SQL. The first file is call can look like this: drwxrwxr-x 3 michael michael 4096 Sep 22 11:16 ..
V1__ Create_person_table.sql. It -rw-rw-r-- 1 michael michael 112
is a DDL file and has the content clean install flyway:migrate Sep 18 07:59 V1__Create_person_table.sql
shown in Listing 2. -Pdb -rw-rw-r-- 1 michael michael 149
The second file is a data manip- Sep 18 07:28 V2__Insert_persons.sql
ulation language (DML) file. To make the call even easier
The file V2__Insert_persons.sql and to gain from other benefits,

JAVA TECH
consists of three statements for such as nice visualization, we will
inserting three rows into the also use Hudson, the continuous
previously created table (see integration engine, for database
Listing 3). migrations. We can trigger the
Now let’s look at the Maven build manually, or let Hudson
project object model (POM), the observe changes in version control
metainformation file of the Maven and perform builds automatically,

ABOUT US
build tool for our project. This is by calling the build scripts. The call
the place to define how Flyway results in some console output, as
will be used and to tell the system shown in Listing 5.
about the database it should con- In our case, the database was
nect to. The logic is placed inside empty and no migrations were run
a Maven profile. Listing 4 shows before. Thus, Flyway does some
the relevant snippet. bootstrapping (creating meta-
Now let’s trig- information, particularly the ver-
ROLE OF DEVOPS ger Flyway via sion number of the schema) Download all listings in this issue as text
DevOps seeks Maven. We’ve
introduced a
and triggers our two migrations’
scripts (because we’ve placed two
to align goals, dedicated profile, SQL files into our directory). +—————————-+ contains metainformation about
concepts, and which we’ll have
to activate. In our
Examining our database, we
now have two new tables, both
| PERSON
| schema_version |
| the database, and migrations on
it—including the information
tools for both simple example, created by Flyway: +—————————-+ about which version the data- blog
development and the migration
itself is started
2 rows in set (0.01 sec) base is currently in—in order to
derive which statements must be
operations. after a Maven
mysql> show tables;
+—————————-+ One table is created by our applied or not, in a specific envi-
installation. Keep | Tables_in_mydb | migration scripts. The other table ronment, with a specific run.
44
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 6 LISTING 7 LISTING 8 LISTING 9

+————-+—————————————-+————————————-+—————-+
| Version | Description | Installed on | State |
+————-+—————————————-+————————————-+—————-+
|1 | Create person table | 2013-09-19 20:52:32 | Success |

JAVA IN ACTION
|2 | Insert persons | 2013-09-19 20:52:32 | Success |
|3 | InsertUpdate persons| 2013-09-19 20:55:52 | Success |
+————-+—————————————-+————————————-+—————-+

JAVA TECH
Figure 3

Now let’s have a quick look command. Triggering Flyway with


into the table PERSON. The table the build tool Gradle, using gradle
has three rows (because the two flywayInfo, delivers the output

ABOUT US
migration scripts created the shown in Listing 6.
table PERSON and inserted three How does Gradle work? Listing 7
entries): shows the Gradle build file that,
from a functional perspective,
mysql> select * from PERSON; pretty much is comparable to our
+—-+———————-+ Maven POM. With Gradle, project
| ID | NAME | and build information are written
+—-+———————-+ with the programming language Download all listings in this issue as text
| 1 | Peter Meyer | Groovy, which is a first-class citi-
| 2 | Peter Bonnd | zen on the Java Virtual Machine.
| 3 | Klara Korn | The file is also part of the source is named V3__InsertUpdate_ our version control system Git, as
+—-+———————-+ code tree in version control, as is persons.sql, includes an update to shown in Listing 9.
3 rows in set (0.00 sec) the case with the Maven POM. an existing row and the creation of Hudson detects changes in Git,
With Flyway, we can choose the a stored procedure, ending with and rebuilds the project accord-
By executing Flyway’s reporting build tool, either Maven or Gradle, a call to that stored procedure to ing to the build scripts, which are blog
features (on the command line or that best fits our requirements. insert a new row into the existing also part of the code tree in version
via Hudson), we can also get infor- Now let’s add another migration table, as shown in Listing 8. control (see Figure 3).
mation about the current state of to the process. Another file, our We can contribute the new arti- The migration framework
migration by triggering a flywayInfo third migration script, which fact by committing and pushing to detects the current version of the
45
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 10

[INFO]
[INFO] --- flyway-maven-plugin:2.1.1:migrate (default-cli) @
devops ---
[INFO] Current version of schema 'mydb': 2

JAVA IN ACTION
[INFO] Migrating schema 'mydb' to version 3
[INFO] Successfully applied 1 migration to schema 'mydb'
(execution time
00:00.069s).

Download all listings in this issue as text

JAVA TECH
database, that is (2), and derives Conclusion
the information to apply the newly This article introduced DevOps, a
available migration number (3), modern way of fostering collabo-
resulting in the output shown in ration between development and
Listing 10. operations. Through shared goals,
We now have a fourth row in shared processes, and shared

ABOUT US
our PERSON table and an updated tools, barriers between different
row, which obviously is a fix of a organizational departments are
previously introduced typo. The minimized.
new row was inserted by call- The article also provided a round-
ing the freshly created stored trip through a concrete example
procedure. that showed processes and tools—
such as Hudson, Gradle, Maven,
mysql> select * from PERSON; and Git—that might shape the
+—-+———————-+ daily collaboration between the
| ID | NAME | different stakeholders and help
+—-+———————-+ to deliver software faster and with
| 1 | Peter Meyer | better quality. </article>
| 2 | Peter Bond |
| 3 | Klara Korn |
| 4 | Donald Luck | LEARN MORE blog
+—-+———————-+ • Agile ALM: Lightweight Tools and
4 rows in set (0.00 sec) Agile Strategies (Manning, 2011)
• DevOps for Developers
Crisp, isn’t it? (Apress, 2012)
46
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
Adding a Member to Your
Development Team

JAVA IN ACTION
EST
NT

B
E
O PM
EL

S
V
DE

CE
P R A C TI
The best and worst ways to manage the addition of a new team member
T. LAMINE BA
BIO

I stare out the window. Adding a new member to right resource for of group develop-

JAVA TECH
NOT SO TRIVIAL
The sun is setting above a team is a seemingly trivial the right job is not ment in 1965. He
the hills. Yet the team of step to take when your soft- a trivial task. So Adding a new argues that team
a dozen Java developers ware development project is before solving the member to a team formation usu-
and I, as the project tech-
nical lead, know that it is
stalling. Yet managers com-
monly find themselves in a
equation at hand,
we should first
is a seemingly ally follows four
predictable and
going to be another long more difficult position upon understand what trivial step consecutive stages.
day at work. We are behind the arrival of the new mem- constitutes a team. to take when During the forming

ABOUT US
schedule, and the customer ber. The reason? The integra- By definition, stage, members
will not settle for less than tion of a newcomer into your and according your software are not clear about
expected. So I try my best team is a sensitive and risky to the Project development the objectives of
to keep a calm and unemo-
tional demeanor in order
event and should be handled
by all leads with great atten-
Management
Institute, a team project is stalling. the group. It is up
to the group leader
to lead my staff with confi- tion and care. includes all stake- to provide direc-
dence, while my gut twists holders of a proj- tion. During the
itself just enough to remind Definition of a Team ect. In this context, storming stage,
me that I should be wor- Michael Levin, a Java however, we are only con- multiple ideas compete with
ried. Excessive overtime has Champion and a founder of cerned with the development one another. Next, during
already exhausted my devel- multiple Java user groups team. That said, as social the norming stage, the goal
opers and, according to my around the world, suggests animals, teaming is a vital has been acknowledged by
calculations, productivity is the following about a team: and inherent part of our exis- all and a common plan is
starting to fall as a result. “Human resources come in tence and survival. To better in place. Finally, during the
Furthermore, cost variance various stages of sharpness. understand its characteris- performing stage, the team blog
analysis of my schedule They all will work, potentially. tics, we have to refer to Bruce is able to reorganize itself
reveals that the best option The trick is to test their cut- Tuckman, who proposed and adapt rapidly to changes
at this time is to add more ting ability before you start.” the “Forming-Storming- caused by environmental
resources to the project. This implies that finding the Norming-Performing” model factors in order to reach high
47
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
performance levels and achieve channels. Tensions and adversity and appreciates the need for more there may already be a strong
specific objectives. should be expected, and soft skills, resources. The lead should also advocacy by the team to bring in
such as good negotiation abilities, prepare for the natural tendency a new resource when required to
Impact of a New Member are required from the lead. During of the team to revert back to the help meet the goals of the group.

JAVA IN ACTION
As discussed earlier, a new team this phase, a new member might storming phase. Then, great nego- It is, then, up to the manager to
member can potentially disturb be easily welcomed into the team tiation skills may move the team monitor closely all indicators sug-
a whole organization. In order to depending, for the most part, swiftly back to norming mode. gesting that the new member is
prevent such a predicament, the on the manager’s competency. The team is in performing stage. not “a good fit” and to take appro-
technical lead has to be aware Hence, the manager ought to be During the performing stage, the priate measures accordingly as
at all times of the stage of the sensitive about the new, informally team’s work is very efficient. The early as possible.
team. The leader must assume created hierarchy within the team, group is able to satisfy all deliv-
that when there is change, teams which matters a lot to the mem- erables under budget and within Politics and Culture

JAVA TECH
tend to revert back to the storm- bers. Furthermore, it is advisable schedule. There usually is a high Politics and culture are also impor-
ing stage in order to adapt. Hence, for the manager to fully disclose level of satisfaction with the work tant facets to consider when
it is important to note that some the role of the new member to conditions among most mem- adding a new member. As a tech-
stages are more desirable than the team and allow the team to bers. This level of productivity is nical lead, it is essential to moni-
others when introducing a new actively participate in the reorgani- not easily nor frequently reached. tor and understand the way the
member into the team. zation that follows. It is also usually short-lived, as team interacts and to share this
Here are a few suggestions on The team is in norming stage. the team may eventually revert information with the new mem-

ABOUT US
how to deal with the situation dur- The team has a clear plan. All back to storming. This is why it ber in order to facilitate his or her
ing each stage. members understand it and have is the worst time to add a new integration into the group. For
The team is in forming stage. In agreed to it. Now, the goal of the member. It is preferable to “ride example, the team may favor a very
most cases, this is the best time to team supersedes the goal of each the wave” as long as quiet working environ-
add a new member, considering member and progress has become possible before initiat- TEAM CULTURE ment, or prefer to meet
that the goal of the project is not
clear to most stakeholders. The
the dashboard of all stakeholders.
At this time, it is very risky to add
ing any reorganization.
However, if the project
It is essential at a specific time of the
day (such as mornings),
new member can easily fit into the a new member; the stakeholders absolutely requires a that the team or choose visuals rather
group and rapidly contribute. might be resistant to any changes new resource immedi- lead monitor than text in their presen-
The team is in storming stage.
At this time, the different team
because they have already worked
hard to reach a consensus. As a
ately, then proceeding
with great caution and
and understand tations. Ultimately, most
trends (from a corpo-
players are discussing and pro- result, it is necessary for the tech- in concert with the team the way the rate culture standpoint)
posing many ideas. Subgroups
are created according to experi-
nical lead to guide and monitor
closely the new member through
is advised. In fact, under
such circumstances,
team interacts should be controlled and
to some extent driven
ences, affinities, or other factors. the team integration process. It many important deci- and share this by the manager. Also, blog
Through self-organization, each is an ideal time to present perfor- sions may be antici- information with the manager should not
subgroup elects its leaders, who
will be responsible for distributing
mance charts, what-if scenarios,
and prediction models to all stake-
pated and proposed by
the developers them-
the new member. expect new members
to learn all the rituals of
the right information across given holders so the team comprehends selves. In other words, the team on their own.
48
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
Taking the time to inform and pre- altering and learning about only

3 Billion
pare new members will reduce the a small part of the system. In the
learning curve. earlier example, assuming that
the new member is responsible

JAVA IN ACTION
Benefits of Good Object- for the “quacking” behavior of
Oriented Design Practices the class animal, he or she may be

Devices Run Java


According to Murphy’s Law, assigned only the associated set
“Anything that can go wrong, of classes corresponding to the
will go wrong.” Following good implementation of this behavior.
object-oriented design practices
becomes helpful when making Conclusion
changes to your organization. It is early morning, and I am the

JAVA TECH
For instance, inheritance in Java first person in the office. I walk Computers, Printers, Routers, BlackBerry Smartphones,
provides the ability for a class to up to the window. I see the most Cell Phones, Kindle E-Readers, Parking Meters, Vehicle
extend or override another class. gorgeous sky slowly fading from
Taking advantage of inheritance a dark orange to a bright yellow. Diagnostic Systems, On-Board Computer Systems,
may facilitate the integration of a I stare and enjoy the beauty of Smart Grid Meters, Lottery Systems, Airplane Systems,
new programmer by allowing him Mother Nature, while review-
ATMs, Government IDs, Public Transportation Passes,
or her to modify only a portion of ing in my head my plan of attack

ABOUT US
the codebase. The coder can also for the day: I will greet this new Credit Cards, VoIP Phones, Livescribe Smartpens, MRIs,
reuse other tested and approved recruit, introduce him to the
CT Scanners, Robots, Home Security Systems, TVs,
modules to experiment with his team, and prepare for the worst
or her application. Furthermore, while expecting the best. Full of Cable Boxes, PlayStation Consoles, Blu-ray Disc Players…
there are many benefits in using confidence, I exhale. Then, I feel a
the method known as polymor- timid touch on my right shoulder,
phism. Polymorphism creates the followed by a soft “Good morn-
ability for an object to contain ing.” I turn around to find a young
other objects, including itself. This man full of energy, yet slightly dis- #1 Development Platform
approach allows a programmer to oriented as it is obviously his first
implement various behaviors of day. He has his hand out, expect-
the same object. As an example, ing a shake. I shake his hand, and
the team could create an object with a greeting smile, I tell him, “It
animal that may have the ability is a good morning, indeed. Please, oracle.com/goto/java
to “quack” if it is a duck or “bark” follow me.” </article> or call 1.800.ORACLE.1 blog
if it is a dog. Such organization of
the code makes it easier for new
members to be functional, con- LEARN MORE Copyright © 2011, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates.
Other names may be trademarks of their respective owners.

tribute, and fulfill their role while • Project Management Institute


49
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
Concurrency Utilities for Java EE

JAVA IN ACTION
Learn how to best execute tasks using application server concurrency services.

JOSH JUNEAU P oor performance can be


detrimental to an applica-
tion’s success. Performance
in the background without
waits occurring.
Java EE 7 includes the con-
new threads in an application
server environment using
java.lang.Thread or java.util
resources are used to
facilitate the use of concur-
rency utilities for Java EE:
BIO Listen
to Josh can be measured in many currency utilities for Java EE, .Timer, because that can lead ManagedExecutorService,

JAVA TECH
Juneau ways. Whether application which standardize a solution to unreliable results. ManagedScheduledExecutor
introduce
the topic of
users can initiate tasks and for using application com- The situation improved Service, ContextService, and
concurrency then move onto others with- ponents and Java EE services when asynchronous ManagedThreadFactory.
utilities in out waiting, or whether a in an asynchronous manner. Enterprise JavaBeans (EJB) These four managed service
Java EE 7.
database needs to be queried The API provides an easy was introduced with Java resources reside within the
and return results without path for those familiar with EE 6, which allowed process- application server for asyn-
blocking a user interface, the Java SE concurrency to use it ing to occur asynchronously chronous execution of tasks,

ABOUT US
bottom line is that waiting for enterprise applications. on a thread other than the obtaining container context,
for tasks to be completed can Before Java EE 6, it was request handling thread. The and the creation of managed
become a user nightmare, more difficult to perform concurrency utilities for Java threads.
making a poorly performing concurrent tasks with server- EE build upon asynchronous The javax.enterprise
application dif- side applications, EJB, and introduce a set of .concurrent.ManagedExecutor
ficult to use. TASK MASTER because applica- application server concur- Service is used to execute
In Java SE, the tion server con- rency services that assist in submitted tasks in an asyn-
idea of thread- Concurrency utilities
tainers typically the asynchronous execu- chronous manner. It is an
ing is a standard in Java EE 7 provide
ran application tion of tasks in an effort to interface that extends its
technique that
is used to help
a solution for component code
on a thread that
provide a more complete
concurrency solution for
Java SE counterpart, the java
.util.ExecutorService inter-
prevent bad user using application
was managed by Java enterprise applications. face. The tasks submitted to
experiences,
because it allows
components and the container,
and container-
In this article, we will cover
each of these services and
a ManagedExecutorService
are executed by threads that
for long-running Java EE services in
supplied object provide usage scenarios. are controlled by the applica- blog
tasks to be an asynchronous access occurred tion server.
Server Resources
spawned into a
separate thread manner. within the same
thread. It is The following applica-
GlassFish 4.x contains a
default ManagedExecutor
and executed unwise to spawn tion server container Service instance that can be
50
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
accessed using the JNDI name of ManagedScheduledExecutorService different concurrency utilities, it The @Resource annota-
concurrent/__defaultManaged with a JNDI name of concurrent/ is possible to generate your own, tion can also be used to inject
ExecutorService or the stan- __defaultManagedScheduled if desired. To do so, you can use the resource into the code, as
dard JNDI name of java:comp/ ExecutorService or the stan- either the GlassFish adminis- needed, by passing the name of

JAVA IN ACTION
DefaultManagedExecutorService, dard JNDI name of java:comp/ tration console or the asadmin the server-side resource instance
as defined in the Java EE 7 DefaultManagedScheduled command-line utility. There are to the annotation. For instance,
Platform specification. Typically, ExecutorService. several attributes you can config- to obtain an instance of the
tasks that make use of the The javax.enterprise.concurrent ure to customize the concurrency ManagedExecutorService by injec-
ManagedExecutorService incorpo- .ContextService is used to create resources, including Deployment tion, you can use the following
rate long-running processes that contextual objects without using a Order, Thread Priority, and more. lines of code:
need to be executed in an asyn- managed executor, by utilizing the For more information on creating
chronous manner so that they java.lang.reflect proxy capabilities such resources, refer to the Java @Resource(name=

JAVA TECH
do not cause other processes to to associate component container EE 7 Tutorial or the Concurrency "concurrent/myMES")
become locked during execution. context with object instances. This Utilities 1.0 specification. ManagedExecutorService mes;
The javax.enterprise.concurrent allows objects to become contex-
.ManagedScheduledExecutorService tual, allowing them to execute Accessing Application Resources The examples demonstrated in
interface is used to execute tasks with the thread context of the In order to submit tasks to the the rest of this article will focus on
that are submitted on a sched- associated component instance. server-side concurrency resources using the @Resource annotation.
uled basis in an asynchronous GlassFish 4.x contains a default for processing, an application

ABOUT US
manner, very much like the ContextService with a JNDI name of must include a reference for the Example Scenario
ManagedExecutorService. This concurrent/__defaultContextService server-side resources, either We will demonstrate the use of
interface extends the java.util or the standard JNDI name of defined within an application’s each different concurrency utility
.concurrent.ScheduledExecutor java:comp/DefaultContextService. deployment descriptors or via using a real-life example applica-
Service and javax.enterprise Lastly, a ManagedThreadFactory the @Resource annotation. For tion, a basic vacation planner for
.concurrent.ManagedExecutor resource can be for creating instance, within a web applica- the Acme World theme park. It
Service interfaces. Again, tasks managed container threads tion, the resources can be defined allows guests to book reservations
managed by this service are that can be utilized to perform within the web.xml file. for park tickets and restaurant
executed by threads that are con- tasks in the background while To register references to the meals. In the examples, the appli-
trolled by the application server other processes are executing. resources within web.xml, entries cation will be used under different
container. The difference between GlassFish 4.x contains a default for any or each of the four inter- scenarios for each concurrent task
the two resources is that this one ManagedThreadFactory with a JNDI faces can be made inside of a demonstration.
has the ability to assume sched- name of concurrent/__default <resource-env-ref> element by
uled execution using delay and ManagedThreadFactory or the assigning a <resource-env-ref- Managed Tasks
periodic task execution capa- standard JNDI name of java:comp/ name> and a <resource-env-ref- The javax.enterprise.concurrent blog
bilities that are made available DefaultManagedThreadFactory. type> for each entry. Listing 1 .ManagedExecutorService interface
by the ScheduledExecutorService Note: While an installation of demonstrates how to register a can be used to create server-side
interface. GlassFish 4.x contains a default ManagedExecutorService within the resources that have the ability to
GlassFish 4.x contains a default server resource for each of the web.xml file. execute tasks in an asynchronous
51
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 1 LISTING 2a LISTING 2b LISTING 3
manner. Classes that contain managed bean action, which will
task implementations to be run invoke a potentially long-running <resource-env-ref>
<description>
asynchronously can be submit- task to query the database and
Reference to ManagedExecutorService
ted to a ManagedExecutorService retrieve reservation information,
</description>

JAVA IN ACTION
for processing. Any class that including information regard- <resource-env-ref-name>
is to be submitted to the ing the cost of each reservation. concurrent/__defaultManagedExecutorSerice
ManagedExecutorService must Because this is a long-running </resource-env-ref-name>
implement either the java.lang task, we’d like the user to receive <resource-env-ref-type>
.Runnable or the java.util an immediate response from the javax.enterprise.concurrent.ManagedExecutorService
.concurrent.Callable interface. server, indicating that the infor- </resource-env-ref-type>
Task classes that implement mation will be e-mailed shortly. </resource-env-ref>
java.lang.Runnable must include Therefore, the task is handed off

JAVA TECH
a run() method, which is invoked to a ManagedExecutorService for
by the ManagedExecutorService. processing, and then control is
Such tasks are useful for running returned to the user. The class that
reports or long-running queries contains the logic for the task is
that are executed in the back- named AcmeReservationReport,
ground. Classes that implement and the code is shown in Listings
java.util.concurrent.Callable must 2a and 2b.

ABOUT US
also implement the ManagedTask To make use of the Acme
interface, allowing the class to ReservationReport, it must be
supply an identifiable name via the submitted to a ManagedExecutor
IDENTITY_NAME property. These Service resource on the server.
classes also must implement the This is typically done by cre-
call() method, which performs the ating an instance of the task
work for the task at hand. Such class and submitting it to the
task classes are used for issuing ManagedExecutorService using its
multiple tasks to be processed submit() method. A Future object
asynchronously. will be returned, which can be
To demonstrate the submission used to determine the status of
of a long-running task, let’s sup- the long-running task. Listing 3
pose that the directors at Acme demonstrates how to submit the
World wish to run a report that task class for processing.
will provide them with a summary In some cases, an application blog
of each park reservation. To initi- requires processing of more than
ate the report, they click a button one long-running task asyn-
that will send them the report via chronously; then the results of Download all listings in this issue as text
e-mail. This button is bound to a each can be processed once they
52
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 4 LISTING 5 LISTING 6a LISTING 6b
become available. Tasks that report. To build the report,
Note: The following listing has been excerpted, as noted by the . . . symbol. The
implement java.lang.Callable are each of the tasks is sent to the
full code listing is available by downloading the code listings for this issue.
appropriate for such cases. ManagedExecutorService sepa-
To demonstrate such a task, rately for processing, and in turn,
public class AcmeParkReservation implements Callable<

JAVA IN ACTION
let’s suppose that a weekly e-mail a Future<Object> is returned for ParkReservation>, ManagedTask {
for guests that have a reservation each. This Future object can be
to Acme World is constructed by used to determine whether the String reportId;
combining the results of queries task has been completed by invok- BigDecimal parkReservationId;
made to both the park database ing the object’s isDone() method, Map<String, String> executionProperties;
tables and the restaurant reserva- and once the task has finished, private ParkReservationFacade parkReservationFacade;
tions tables. To do so, two tasks are it can be used to obtain infor-
submitted, one to query the park mation from the object that is public AcmeParkReservation(String reportId,

JAVA TECH
reservation and the other to query returned by invoking the object’s BigDecimal parkReservationId,
the restaurant reservations. Once get() method. Listings 6a and ParkReservationFacade parkReservationFacade){
the tasks have completed, they are 6b contain the sources for the this.reportId = reportId;
processed together to formulate AcmeSummaryEmailController JSF this.parkReservationId = parkReservationId;
the content for the e-mail report. controller. this.parkReservationFacade = parkReservationFacade;
Listing 4 contains the source A ManagedExecutorService
executionProperties = new HashMap<>();
code for the AcmeParkReservation instance can be used by multiple

ABOUT US
executionProperties.put(
task; Listing 5 contains the source application components at a time,
ManagedTask.IDENTITY_NAME, getIdentityName());
code for the AcmeRestaurant and each task becomes contextual, }
Reservation task. Each of these meaning that it will retain the con-
tasks implements Callable and the text of the submitting component. public String getIdentityName() {
ManagedTask interfaces. The con- The task is then executed within return “AcmeParkReservation: reportId=” +
structors accept the arguments the context of the submitting com- reportId + “, parkReservationId=” + parkReservationId;
that will be needed to execute ponent. A ManagedExecutorService }
the task, and the call() method instance can be terminated or
performs the long-running imple- suspended when the server itself @Override
mentation. In this case, the data- is shut down, or when applications public ParkReservation call() throws Exception {
base is queried within each of the or components are disabled or // Perform long-running task
tasks, and information is then removed. return parkReservationFacade.findById(parkReservationId);
returned for further processing. }
The AcmeSummaryEmail Scheduled Tasks ...
} blog
Controller JavaServer Faces The javax.enterprise.concurrent
(JSF) managed bean control- .ManagedScheduledExecutorService
ler is used to process each of the can be used to execute tasks at
two tasks and then combine the specified times. Interfacing with Download all listings in this issue as text
results to formulate the e-mail the ManagedScheduledExecutor
53
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 7 LISTING 8
Service is very similar to working AtFixedRate method is invoked,
Note: The following listing has been excerpted, as noted by the . . . symbol. The
with the ManagedExecutorService which accepts the Runnable, the
full code listing is available by downloading the code listings for this issue.
in that any task classes must initialDelay, the period of time,
implement either the java.lang and the time unit. In the exam- public class AcmeReservationCount implements Runnable,

JAVA IN ACTION
.Runnable or the java.util ple, the time unit is TimeUnit Serializable {
.concurrent.Callable interface. The .MINUTES. The scheduled man- ParkReservationFacade parkReservationFacade =
only significant difference between aged task is implemented within lookupParkReservationFacadeBean();
these two types of concurrency a servlet context listener named String reportName;
resources is the scheduling ability AcmeWorldServletContextListener. ...
that is specified when submitting a At application startup, the context
public void run() {
scheduled task. is initialized and the task is sched-
runCountReport();
Listing 7 shows a task class, uled to be executed once an hour.

JAVA TECH
}
entitled AcmeReservationCount, A ManagedScheduledExecutor
which is used to periodically poll Service instance is capable of being /**
the Acme World reservation data- utilized by multiple applications * Prints a count of reservations.
base to see how many new res- and components at a time. Each */
ervations have been made. Note task that is submitted to the ser- public void runCountReport() {
that the implementation does vice is contextual, and the context System.out.println("Park Reservation Count for Today");
System.out.println("===============================");
not contain any scheduling infor- of the thread running the task is

ABOUT US
Long reservationCount =
mation, but only provides a task changed to match that of the task parkReservationFacade.findCount();
implementation. instance while it is being executed. System.out.println(reservationCount);
As mentioned previously, The context is restored once the // Email in production application
scheduling occurs at task sub- task is completed. }
mission time, and Listing 8 dem-
onstrates how to submit the Creating Contextual Objects private ParkReservationFacade
AcmeReservationCount class to the The javax.enterprise.concurrent lookupParkReservationFacadeBean() {
ManagedScheduledExecutorService .ContextService interface can try {
Context c = new InitialContext();
for processing. In this case, be used for creating contextual return (ParkReservationFacade) c.lookup(
the task will be executed every objects without the use of a man- "java:global/JavaMagazineEE7/ParkReservationFacade");
60 minutes, and it will log a aged executor. This is achieved by } catch (NamingException ne) {
count of new reservations that using the dynamic proxy capabili- ...
have been made within the ties of the java.lang.reflect package, }
past 60 minutes. This schedul- associating the application com- }
ing is done by calling one of the ponent context with the object } blog
ManagedScheduledExecutorService instances that are created. This
methods, which are inherited from service can be used to develop
the java.util.concurrency interfaces. custom concurrent applications Download all listings in this issue as text
In this example, the schedule and services, allowing for the
54
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 9 LISTING 10 LISTING 11
creation of custom Java EE com- tions. The ContextService is used
ponents, such as ExecutorService to create a contextual proxy for @Singleton
public class ExecutorAccessor {
implementations. each AcmeSingleReservation call,
Contextual object proxy and that proxy is then submitted
private ExecutorAccessor executorAccessor;

JAVA IN ACTION
instances are created by calling to the thread pool that is retrieved private ThreadPoolExecutor tpe;
upon a ContextService instance from the ExecutorAccessor @Resource(name = "concurrent/__defaultManagedThreadFactory")
createContextualProxy() method. Singleton EJB. The reservation ManagedThreadFactory threadFactory;
Task instances must implement objects are then returned by call-
the Callable interface, and the ing the thread pool take().get() @PostConstruct
call() method contains the task method chain. Listing 11 contains public void postConstruct() {
implementation. The example in the complete implementation for tpe = new ThreadPoolExecutor(
this article demonstrates how to ReservationChecker, the stateless 5, 10, 5, TimeUnit.SECONDS,

JAVA TECH
generate a custom Singleton EJB session bean that contains this new ArrayBlockingQueue<Runnable>(10),
that can be used for generating implementation. threadFactory);
a managed thread pool execu- }
tor. Listing 9 contains the code for Server Threads
ExecutorAccessor, the Singleton Server-side thread instances public ExecutorService getThreadPool() {
EJB that is used for creating a can be created using the return tpe;
}
managed thread pool executor, javax.enterprise.concurrent

ABOUT US
}
which will be used to submit the .ManagedThreadFactory interface.
contextual task instance. Spawning server-side threads
The task in this example is can be beneficial when there is a
implemented in a class named requirement to execute a long-
AcmeSingleReservation (Listing 10), running task without producing a
which accepts a reservation ID bottleneck within an application.
number and queries the database New threads can be created by
to return the matching reservation calling the java.util.concurrent
record object. The call() method .ThreadFactory interface’s
in the class creates a database newThread(Runnable r) method,
connection, queries the specified passing the Runnable class to be
reservation, and returns the object. executed. Once created, the newly
The task is invoked via a state- created thread’s start() method
less session EJB that passes a can be invoked to start the thread
given reservation ID number to the within the context of the applica- blog
AcmeSingleReservation task class, tion component instance.
returning the reservation object. It For example, let’s assume
does so by using different threads that the Acme World appli- Download all listings in this issue as text
to retrieve each of the reserva- cation is going to poll the
55
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//enterprise java /

COMMUNITY
LISTING 12 LISTING 13 LISTING 14 LISTING 15
RestaurantReservation entity transaction that is active in an exe-
Note: The following listing has been excerpted, as noted by the . . . symbol. The
periodically to see if a new res- cuting thread will be suspended.
full code listing is available by downloading the code listings for this issue.
ervation has been made, and Listing 15 illustrates how a task can
then send alerts accordingly. A interact with transaction-capable public class ReservationAlerter implements Runnable {

JAVA IN ACTION
Runnable class can be created to resources in a single transaction.
house the procedure for polling @Override
the database and creating the Conclusion public void run() {
alerts. Listing 12 shows the code The days of developing custom while (!Thread.interrupted()) {
for the Runnable that will be used solutions to deal with multi- reviewReservations();
to create the managed thread threaded enterprise applications try {
in this example, a class named are over. The concurrency utili- Thread.sleep(100000);
ReservationAlerter. That class can ties for Java EE provide a standard } catch (InterruptedException ex) {

JAVA TECH
then be made into a thread by solution for concurrency in enter- // Log error
calling a ManagedThreadFactory’s prise applications, which supports }
newThread() method, as shown in simple and advanced concurrency }
Listing 13. patterns. Those who are familiar }
Listing 14 shows the complete with using concurrency APIs under
public Collection reviewReservations() {
code for obtaining a reference to Java SE will have no problem learn-
Connection conn = null;
the ManagedThreadFactory via ing how to utilize the concurrency

ABOUT US
Properties connectionProps = new Properties();
@Resource injection, creating the utilities for Java EE, because both connectionProps.put("user", "user");
new Thread instance, and then APIs follow similar guidelines. connectionProps.put("password", "password");
starting it. For beginners, the API is straight- Collection reservations = null;
forward and intuitive. try {
Utilizing Transactions To see the examples used in // Obtain connection and retrieve reservations
The concurrency resources support this article in action, download conn = DriverManager.getConnection(
user-managed global transaction and create a NetBeans project "jdbc:derby:acme;create=false",
demarcation via the javax using the article sources. Then connectionProps);
.transaction.UserTransaction inter- create the database using Apache // Use the connection to query the database for reservations
face. This allows transactions to Derby, which comes packaged } catch (SQLException ex){
begin via the begin() method, with GlassFish. Finally, deploy System.out.println("Exception: " + ex);
commit via the commit() method, the application project to your } finally {
and roll back via the rollback() GlassFish server. </article> . . .}
return reservations;
method, if needed. Any managed
} blog
task instances are run outside of
LEARN MORE }
the submitted thread’s transaction
scope. This means that the execu- • The Java EE 7 Tutorial
tor is responsible for coordinat- • JSR 236: Concurrency Utilities for Download all listings in this issue as text
ing transactional actions, and any Java EE
56
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//mobile and embedded /

COMMUNITY
Internet of Things 101

JAVA IN ACTION
Explore concepts and issues relevant to the Internet of Things by creating an embedded application.

ERIC J. BRUNO M any companies are


promising a future
where all the smart com-
readers, and modern home
appliances play a role in the
world of M2M and IoT as
sensors. Ashton’s vision was
to create a global system of
computers, devices, and sen-
standard platforms, and cre-
ate an ecosystem in which
all parties stand to gain. The
BIO
puting devices around us well. Basically any electronic sors that feed on their own IoT is in its very early stages,

JAVA TECH
will communicate with one endpoint capable of being data, instead of being depen- and it’s an exciting time to be
another—and with the enter- uniquely identified, with per- dent solely on humans for part of its formation.
prise applications we use tinent resource or location data input. As a result, the
most—in what some call a data, qualifies as a usable system can have an under- Java and IoT: A Platform for
machine-to-machine (M2M) device in an IoT architecture. standing of where everything Hyperconnectivity
architecture. Oracle has a The amount of data and is and what’s taking place Java was born on an embed-
plan here as well, focused the utility each type of device at any location and point in ded device. Initially part

ABOUT US
on the Internet of Things provides might vary, but time. This would lead to a of the Green Project to
(IoT). Although achieving when combined in large world of connected systems power the Star7 handheld
this promise might sound as quantities, tremendous value that could greatly reduce device, Java went on to see
simple as enabling Bluetooth can come from even the sim- waste, lower costs, and enormous success in both
or Wi-Fi on a mobile device, plest data. The key is identi- eliminate loss (however you the web and embedded
making the most of the con- fying and connecting all the define it) for just domains. Perhaps
nected future requires much devices together so that they about any human- no other tech-
THE RIGHT STUFF
deeper integration. can communicate and even machine activity. nology today is
collaborate; this is where the As researchers Perhaps no other better positioned
What Is a Device?
The first step when plan-
internet plays a role. are scrambling to
resolve issues—
technology to power an IoT
strategy than Java.
ning an IoT architecture and The Internet of Things such as address- today is better Given its abil-
strategy is to define what In 1999, Kevin Ashton—the ability, communi- positioned to ity to run on a
a device is. Most people
initially define a device as
cofounder of the Auto-ID
Center at MIT—coined the
cation standards,
battery power, power an Internet wide range of
devices—from blog
a smartphone or a tablet, term Internet of Things to and data collec- of Things strategy feature phones
but smaller, less-powerful
phones also qualify. Sensors,
define a system in which the
internet is connected to the
tion—enterprises
are rushing in to
than Java. with limited CPU
and memory to
electrical controllers, RFID real world via ubiquitous fill the gaps, define rackmounted
57
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//mobile and embedded /

COMMUNITY
servers with immense power and
capacity—Java is meant to power
a world of compute resources with
ubiquitous connectivity, otherwise

JAVA IN ACTION
known as hyperconnectivity. Java-
powered devices in this ecosystem
will communicate with each other,
with users, and with the real world
via sensors and relays to gather
knowledge—and, ultimately,
understanding—about the world
around us in real time.

JAVA TECH
Imagine the rich informa-
tion that can be discovered and
reported in the areas of health-
care, automotive (aka telematics),
building and industrial automa- Figure 1
tion, smart metering, transporta-
tion, logistics, and so on. Here are Oracle is helping to define a However, a complete IoT archi- critical to know the reliability and

ABOUT US
just a few examples: standard IoT platform based on tecture goes beyond Java and true identity of sensors in your
■■ Potentially fatal mistakes can Java, with Java-based middleware, simply identifying a software suite. network as they report informa-
be prevented when automated data storage, and analytics—all It requires a managed solution in tion. Additionally, due to govern-
devices crosscheck a patient’s with the appropriate hardware— which the key benefits are end- ment regulations and ethics in
allergies against medication so that developers can focus on to-end security and the ability to real-world scenarios, you need to
in bottles that identify their innovation and solutions (see expand and scale to future needs, ensure data not only stays out of
contents. Figure 1). Using Oracle Java ME meet industry requirements for the wrong hands, but that only
■■ Traffic conditions can be Embedded in sensors helps ensure standards and security, reduce those authorized to view the data
improved when telematics sys- systems can be built efficiently, costs in terms of IT infrastructure, are allowed to do so (for example,
tems inside vehicles automati- using the same language through- integrate with existing systems, a doctor making a medical diag-
cally alert and reroute drivers out the end-to-end solution with and perform well enough at every nosis for a specific patient).
before congestion occurs. device portability and ongoing layer. Let’s look at Oracle’s IoT Provisioning new devices, identi-
■■ Electricity generation can be support. Oracle Java SE Embedded platform now in more detail. fying where data originates in your
made more efficient if gateway and Oracle Java Embedded Suite Provisioning and management. network, and giving permission
devices within homes and help to further provide the capa- Devices, data, and users need to the right users at the right time blog
office buildings help to more bilities needed to deploy fast, to be identified, authenticated, are all crucial functions required in
accurately report and predict low-cost M2M gateways with data and authorized at each point of an IoT platform. Having the ability
peaks and valleys in demand capture, event processing, and an IoT solution. For example, to efficiently (and centrally) man-
over time. analytics performed end to end. before making decisions, it’s age expanding networks of small
58
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//mobile and embedded /

COMMUNITY
sensors and distributed compute thousands of endpoints in your cloud or the middle tier of your
IoT at JavaOne 2013 nodes is also required.
Security. As mentioned above,
network, you need to gain action-
able insight into your data in real
architecture, or in a relational
database in your data center or
Throughout JavaOne and Oracle
OpenWorld, the movements of attend- user and device identity is part of time. Complex event processing private cloud.

JAVA IN ACTION
ees were tracked by IoT in Motion, application security. Oracle’s IoT software built into your IoT plat- An IoT platform helps store
an Internet of Things collaboration architecture defines entry points to form provides the ability to filter data in the right locations based
between Oracle, Eurotech, Hitachi customers’ LDAP systems for user or make decisions on data before on structure and retrieval needs.
Communication Technologies America identity management, network sending all of it to your data cen- Balancing the need to quickly
(Hitachi CTA), and Hitachi Consulting, equipment and industry-standard ter. Doing so helps retrieve data without
that counted and tracked conference protocols for secure communica- reduce bandwidth GOING DEEP sacrificing security
tion, and safe offsite data storage and processing needs and data integrity is
attendees in various locations.
for scenarios in which this is a (and costs) in your Although achieving the job of the IoT plat-

JAVA TECH
Oracle’s Jennifer Douglas pro-
vided a technology overview: “Hitachi requirement. End-to-end security back-end systems. the promise of the form, not an applica-
Consulting helped build the actual must be well defined and enforced,
yet be flexible enough to allow sys-
The result is a more-
responsive system, “Internet of Things” tion concern.
Big data and analytics.
application that is running the data,
using an Oracle Exalytics box and the tem expansion and usefulness. since automated deci- might sound as simple Analyzing the poten-
Oracle Business Intelligence dash- Connectivity. Device connectiv-
ity begins with basic protocols
sions are made closer
to their datasources
as enabling Bluetooth tially huge amounts
of data captured
board. Hitachi CTA has their SuperJ
running in conjunction with Oracle such as Ethernet, but standards and the systems that or Wi-Fi on a mobile from your devices

ABOUT US
Java SE Embedded through a gate- of communication for sensors and need to act on them, device, making can reveal a plethora
way to the Eurotech Everyware Cloud,
which collects the raw data. Then the
sensitive data must also be sup-
ported. For instance, there are
as opposed to making
decisions centrally. the most of the of hidden value.
There are generally
Exalytics box compiles the data and industry protocols such as DASH7 Storage. Data, espe- connected future two types of analyt-
converts it into something we can for wireless sensor networks,
ZIGBEE for electrical controllers,
cially from sensors in
the real world, comes
requires much ics: real-time ana-
lytics and historical
actually utilize.” All of the technology
ran on Java. 6LoWPAN for building automa- in many shapes and deeper integration. analytics.
While IoT in Motion can distinguish tion and smart grid applications, sizes. From struc- With real-time ana-
a dog or a vehicle from a person, the COSEM for smart metering, and tured relational data lytics, data is analyzed
stereoscopic camera merely registers Bluetooth for a wide range of uses to unstructured, as it’s collected from
and counts people going in and out such as telematics systems. random data, all the information devices and potentially combined
of the spaces without monitoring any Beyond protocols, an IoT plat- your IoT system captures must be with other data to make dynamic
features of individual people. form needs to account for devices collected, stored, retrieved, and decisions. This tends to work best
—Janice J. Heiss that might lose and gain connec- analyzed to mine its full value. This when it’s performed as close to the
tivity repeatedly while being used, data must be stored properly and devices as possible. Historical ana- blog
and ensure that data is stored and securely at each layer, whether it’s lytics involves data captured over
later forwarded as needed. in memory within Oracle Berkeley time, perhaps even years, to look
Event processing. As data is col- DB on a local device or gateway, for correlations between applica-
lected from the hundreds or in a NoSQL database in a public tions and user-specific trends.
59
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//mobile and embedded /

COMMUNITY
Historical data sets can grow to
enormous sizes over time and,
therefore, the analytics are usually
run within the data center as close

JAVA IN ACTION
as possible to the data stores.
Big data is a term used to
describe a collection of data sets
so large and complex that it’s
difficult to process using tradi-
tional database management
tools and algorithms. Analytics
solutions meet the challenge of

JAVA TECH
storing, indexing, searching, visu-
alizing, and drawing inferences
and conclusions from these large
data sets. IoT platforms need to
integrate structured and unstruc-
tured data, perform map-reduce
operations on the data, and sup-

ABOUT US
Figure 2 Figure 3
port various file systems such
as the Hadoop Distributed File
System (HDFS). an electrical device or to pro- a browser. This will allow the ple, we’ll choose Oracle Java SE
As mentioned above regarding gram appliances, such as a dish- homeowner to access the home Embedded. Having the ability to
event processing, performing edge washer, to turn on only when the gateway from a desktop, laptop, run with as little as 32 MB of mem-
analytics at locations physically price per watt-hour for electricity or smart device no matter where ory, Oracle Java SE Embedded
close to data collection and cura- drops below a certain thresh- the homeowner is—security con- strikes a balance between the
tion might yield a more hierarchi- old. Integrating the gateway with cerns aside. requirements of standard Java
cal system capable of reduced a smart meter, which is itself a Note: The source code for the and embedded development.
response times. gateway for the power company, a example described in this article Additionally, it fits our require-
true IoT solution can be built that can be downloaded here. ment to run an embedded web
A Working IoT Example offers benefits to everyone: the Coffee and dessert. In an embed- server to power our Java servlet.
As an example of Java in an consumer enjoys lower electric- ded context, you have a choice To begin, download Oracle Java
embedded, IoT scenario, let’s ity costs, and the power company between Java ME and Java SE. The SE Embedded, and then install it
build the foundation of a home manages demand more effectively. target device capabilities, applica- by unpacking the .tar file in your blog
gateway server using a 512 MB To make the solution more tion, and other factors will affect home directory on your Raspberry
Raspberry Pi. You can envision realistic, we’ll deploy the applica- your decision—for example, Java Pi using the following command:
this gateway being used by a tion as a Java servlet so that it can ME requires fewer resources,
homeowner to remotely control be accessed and controlled from such as RAM—but for our exam- ~ $ tar xvf <filename>.tar
60
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//mobile and embedded /

COMMUNITY
LISTING 1 LISTING 2
You can test your installation by device. In our case, this pin will
running ~/ejre1.7.0_40/bin/java connect to a PowerSwitch Tail import com.pi4j.io.gpio.GpioController;
...
–version, replacing the directory device, which accepts a low-power
name with the name of the instal- connection to turn an internal AC
@WebServlet(urlPatterns = {"/Gateway"})

JAVA IN ACTION
lation directory. relay switch on and off, thereby public class Gateway extends HttpServlet {
Next, to run our servlet applica- controlling any attached electrical private static final long serialVersionUID = 1L;
tion, you can use Apache Tomcat, components, such as a light (see
IBM’s WebSphere Liberty Profile, Figure 3). final GpioController gpio =
Oracle Java Embedded Suite, or The PowerSwitch Tail plugs into GpioFactory.getInstance();
any others designed to run in an AC power on one end and controls
embedded context. Being based any AC component plugged into final GpioPinDigitalOutput pin =
on the standard Servlet specifica- the other end. The remaining code gpio.provisionDigitalOutputPin( RaspiPin.GPIO_01,

JAVA TECH
tion, our servlet code should work in the servlet simply turns Pin 1— "SmartGrid",
equally well within each server, and any component connected— PinState.LOW);
with only slight differences in how on or off via a URL (see Listing 2). ...
it gets deployed. For this article, To test the servlet, I deployed
we’ll focus on the code itself. it to the servlet engine running
We begin with NetBeans by on my Raspberry Pi, and from
creating a new “Java Web” type of a browser I entered the follow-

ABOUT US
application (as shown in Figure 2). ing URL to set Pin 1 to “high”:
In my case, I chose GlassFish as the http://<IP address of Pi>/
target host, and I used Oracle Java SmartGrid/Gateway?power=on.
Embedded Suite on my Raspberry Doing this after properly hook-
Pi to host the servlet. This configu- ing up the PowerSwitch Tail to
ration allowed me to easily do local the Raspberry Pi, plugging the Download all listings in this issue as text
development and debugging with PowerSwitch Tail into AC power,
a similar deployment environment and plugging a component—such
on my Raspberry Pi. as a desk lamp—into the other small embedded devices such as prepared to help you succeed in
My servlet is named Gateway, end of the PowerSwitch Tail will the Raspberry Pi, and the avail- your new IoT projects now and in
and it uses the Pi4J library remotely turn on the component. ability of a wide range of tools and the future. One set of tools, one
to enable easy access to the To turn it off, simply change the libraries, you can enter the world language, and a set of integrated
Raspberry Pi’s general-purpose value of the power parameter to of IoT without learning a brand- and high-performance Java Virtual
input/output (GPIO) pins from off: http://<IP address of Pi>/ new skill set. Gone are the days Machines (JVMs) are available to
Java. The code shown in Listing 1 SmartGrid/Gateway?power=off. of building your own tool chain enable you today. </article> blog
defines a variable to represent with cross compilers and other
Pin 1 on the Raspberry Pi. Conclusion specialized tools, requiring you
Setting Pin 1 to “high” sends Thanks to the power and versa- to be proficient in multiple pro- LEARN MORE
3.3 volts of power to a connected tility of Java, its ability to run on gramming languages. Java is truly • Oracle Java Embedded
61
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013
//fix this /

COMMUNITY
Hint: Type parameters
are removed at compile
time.

In the September/October 2013 issue, polyglot


developer Attila Balazs gave us a class initialization code 2 THE CODE

JAVA IN ACTION
challenge. He presented us with code that deadlocks or throws What needs to be fixed in the class Sample?
a NullPointerException but never runs to the end correctly import java.util.ArrayList;
and asked us for a fix. The correct answer: both #1 and #3. import java.util.HashMap;
The root cause of the problem is that we manage to call the
public class Sample{
classloader from two separate threads and deadlock it:
From AppThread we reference App, which means that the
■■
public <T> void setArrayList(ArrayList<T> arrayList, T t){

JAVA TECH
class must be loaded and initialized. During the initialization }
we need to load (and initialize) Controller, however. public <T> void setArrayList(ArrayList arrayList, Object obj){
From main we are already loading it, thus the main thread
■■ }
waits after AppThread to load/initialize the App class while
public <T extends HashMap<K,V>> void setArrayList(ArrayList<T>
AppThread waits after main to initialize the Controller class. arrayList){
}
If we change Integer to int, the compiler would see RETRIES as

ABOUT US
a constant and inline it, eliminating the dependencies between the }
two classes. Also, if we move RETRIES into Controller (where
it belongs, because it is referenced only from that class) the
dependency would be broken again. 31) Y ouWHAT S THE FIX?
This issue s challenge comes from Oracle ACE and NuBean
can t have three methods named setArrayList. Remove the last
Consultant Deepak Vohra.
method named setArrayList.
2) Type parameter T cannot extend HashMap<K,V>.
3) If some of the methods are generic, the class must be generic.
1Generics
THE PROBLEM 4) Remove one of the first two methods and add the type parameters
K and V to the third method.
are a relatively new addition to Java (introduced
in Java SE 5), and it is not always clear how they can
be used.
blog

GOT THE ANSWER?


ART BY I-HUA CHEN Look for the answer in the next issue. Or submit your own code challenge!
62
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2013

You might also like