Java Magazine JulyAugust 2012

You might also like

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

//JULY/AUGUST 2012 /

DEVELOPER POWER
With a bevy of cloud-based
tools available, its a great time
to be a Java developer 34

Jenkins NEXUS IVY MAVEN Gradle


ANTHUDSON JREBEL VISUALVM ARTIFACTORY

16 31 45
QuantCell Adam Bien on Fork/Join
Research: His Java EE 6 Framework
Building a Better Stress Test for Client
Spreadsheet Monitoring Tool Java Applications

ORACLE.COM/JAVAMAGAZINE
//table of contents /

COMMUNITY
COMMUNITY 50
02 Java Architect
From the Editor How to Modify javac

JAVA IN ACTION
Change javac to implement
04 new language syntax features.
Java Nation
54
11 Rich Client
JCP Executive Series Lazy Evaluation, Lazy
Q&A with Gil Tene Initiation, and Custom
Azul Systems CTO discusses Bindings in JavaFX 2
Java and the JCP. Jim Weaver on the lazy way

JAVA TECH
to get things done
JAVA IN ACTION 58
20 Enterprise Java
Direct Connection Threading and
Why Java is the right choice Concurrency
for priceline.com The importance of centralized
resource management
JAVA TECH

ABOUT US
24 64
New to Java Mobile and Embedded
Learning and Teaching Wirelessly Back Up
Object Orientation Your Devices
with BlueJ Address Book
A systematic and experimen- Create a MIDlet to schedule a
backup of your address book.
34 16 31 45
tal approach to learning Java
27 67
New to Java Mobile and Embedded Tools Java in Action Q&A Java Architect

DEVELOPER
Introduction to Web Oracle Berkeley DB
Java Editions Java API BUILDING TALKING WITH FORK/JOIN
Service Security A BETTER ADAM BIEN FRAMEWORK
Ted Neward shows us how

POWER
Secure your Web services. SPREADSHEET A Java Champion FOR CLIENT
this Java API works. on his Java EE 6
40 Java powers analytic JAVA APPLI-
Java Architect 71 breakthroughs at stress test CATIONS
HotSpots Fix This QuantCell Research. monitoring tool A great match for blog
Try our ConnectionPool.java With a bevy of cloud-based tools
Hidden Treasure CPU-intensive
available, its a great time to be a Java
Try this debugging tool. code teaser. client-side
developer.
applications

PHOTOGRAPH BY BOB ADLER


01
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//from the editor /

COMMUNITY
J

JAVA IN ACTION
GIVE BACK!

JAVA TECH
ava developers are known to be passionate, even religious, about their IDEs and other tools. With the
emergence of a whole slate of new open source and commercial tools (virtually all of them cloud-based) over ADOPT A JSR
the past five years, theres an awful lot to be passionate about.
There are several reasons for this Cambrian explosion of solutions in this area. For one, agile development
practices, which are now extremely common on a global scale, cry out for collaborative tools that make the
continuous build process manageable. Development teams are also more geographically dispersed than ever Find your JSR here

ABOUT US
before. Furthermore, the popularity and easy availability of many thousands of open source modules and
frameworks, which are otherwise often integrated into an applications code base without much regard for
their provenance, make code governance a bit more important than in the past.
There is also a cloud-related factor to be considered on the supply side of the equation: cloud comput-
ing has simply made it possible for many of these solutions to be brought to a broad market in a relatively
frictionless way. Furthermore, online communities like Java.net and GitHub have wrapped up some of these
technologies in nice social packages that speed adoption through network effects.
But enough abstract discussion. Jump to this issues special feature on the topic, //send us your feedback /

Developer Power (not intended to be exhaustive, just representative). Well review all
suggestions for future
Speaking of passion: Zoran Severacs Java People performance impressed us so
improvements.
much that were opening a general Java Nation call for songs. If youre a songwriter Depending on volume,
who appreciates Java and the Java community, send us a link to your composition. It some messages may
may become our official Java Nation anthem! not get a direct reply. blog

Justin Kestelyn, Editor in Chief BIO

PHOTOGRAPH BY BOB ADLER

02
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
Answers. Fast.

Subscribe and gain instant cutting-edge


development insight from the worlds most
trusted tech publishers all in one
on-demand digital library.
Get unlimited access to 20,000+ online books
and training videos from100+ publishers

S
 earch full text to efficiently get the answers
you need

M
 ake notes and organize content into folders
you control
E
 levate your career with thousands of top
business and professional development titles

ANYTIME, ANYWHERE:
Access Safari Books Online on virtually any device with a browser.

Start a free unlimited-access trial today safaribooksonline.com/javamag


//java nation /

COMMUNITY
The Zone will be the hub of
JavaOne activity September
30October 4.

JAVA IN ACTION
Keynotes. The confer- JavaOne
ence kicks off on Sunday,
September 30, with the
Russia 2012
Java Strategy, Partner, and
Technical keynotes beginning
at 4 p.m. To accommodate
the ever-growing number of
attendees, keynotes will be

JAVA TECH
held at the historic Masonic
Auditorium on Nob Hill. After
the keynotes, attendees can
head to the official JavaOne Attendance topped 2,000
Open House at the Taylor at JavaOne Russia, April
Street Caf in the Zone. 1718, in Moscowclearly
Sessions. Sessions start showing that interest in

ABOUT US
on Monday, October 1, and Java technologies in Russia
attendees can choose from is on the rise. At the Core

GET READY FOR


hundreds of expert-led Java Platform keynote,
technical sessions, hands-on Oracles Georges Saab

JAVAONE 2012
labs, panel discussions, and (above right) and Mike
birds-of-a-feather sessions. Check out the JavaOne 2012 track Lehmann (above left) spoke
titles and descriptions. to a packed house. JavaOne
Exhibition Hall. The Java Exhibition Hall brings innovation and prac- Russia featured more
JavaOne 2012 comes to San Francisco, California, September 30 tical learning into one convenient location: the Zone, which features than half of its sessions in
October 4. Its time to make your plans, because you wont want to exhibitor booths, technology demonstrations, partner exhibits, and Russian, and Java booths
miss this conference. JavaOneknown for its educational offerings, more. Dont miss the chance to network with Java experts, develop- were staffed by at least
community, and networkingis a place to improve your working ers, Oracle and its partners, and architects from around the world. two engineers. A highlight
knowledge and coding expertise, learn from the worlds foremost Rock stars. This years conference will again feature JavaOne rock included the Hackzone,
Java experts, meet with fellow developers in formal and casual set- star speakers, recognized for both their Java technical expertise and where participants could
tings, and enjoy one of the worlds great cities. their speaking skills in the events highest-rated sessions. bring their issues and get
This years JavaOne promises a wealth of content focused on the Java University. The Java University preconference gives you a chance suggestions immediately. blog
evolution and future of Java technology as well as tools, resources, to get even more from your conference experience by attending a full
and best practices that developers need to design and build rich, day of in-depth Java training delivered by experts on Sunday, before
compelling, and individualized services across diverse technologies. the conference officially kicks off with the opening keynote at 4 p.m.
Conference planning is still under way, but here are the highlights: Register. Make your travel and lodging plans, and register now!
PHOTOGRAPH BY SAUL LEWIS 04
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java nation /

COMMUNITY
Java.nets Java

JAVA IN ACTION
Left to right: JavaOne India
attendees learn hands on;
Oracles Nandini Ramani
Tools Community
provides a technology The Java Tools
roadmap; attendees discuss
what sessions to attend. Community is one
of the most active
communities on Java.net. Led by
Fabiane Bizinella Nardon, Anton
(Toni) Epple, and Daniel Lpez

JAVA TECH
Janriz, the community supports
the development of open source
Java development tools on Java
.net, offering guidance and feed-
back to Java Tools project leaders
and visibility to their projects.
Key projects associated with
the Java Tools Community

ABOUT US
include VisualVM (a tool that
visually integrates command-
line JDK tools and lightweight

JAVAONE INDIA 2012 profiling capabilities); Hudson


CI (a continuous integration [CI]
tool); Jailer (a tool that provides
data exportation of referentially
More than 2,000 people attended JavaOne the focus on the cloud for Java EE 7, and the at night. The developer, Santosh Ostwal,
intact row sets); ThreadLogic (a
India, held May 34 in Hyderabad. This Java SE and ME/embedded convergence. came on stage to discuss his application and
graphical interface for analyz-
regional JavaOne conference included Oracle has aggressive plans for Java over encouraged developers to use their creativ-
ing Java thread dumps); Java
informative keynote and technical sessions, the next few years, and we are continuing ity to solve problems. Dont think of it as
Application Bundler (a tool that
hands-on labs, and an Oracle Technology to drive technical advancements across the a phone; think of it as a low-cost wireless
packages a Java application as
Network room for community-related platform, Gaur said. device, he said. See Nano Ganesh in action.
a Mac application bundle); and
presentations. At the Nokia keynote, Gerard J. Rego, head In the technical sessions and at the
JTHarness (a fully featured test
The Java Strategy keynote reminded the of ecosystem and developer experience at booths, there was lots of interest in JavaFX,
framework that facilitates com-
Indian Java community of the power and Nokia, provided an overview of the state of Java EE 6, JDK 8/9/10, and Project Avatar. In
prehensive unit testing).
strength of Java and reaffirmed Oracles mobile technology. The keynote included a addition, many Java user group (JUG) lead- blog
If you have an idea for an open
commitment to Java. Oracle Java engineer- video about a cool mobile application called ers from across India came to JavaOne India
source Java tool, consider hosting
ing executives Nandini Ramani and Anil Gaur Nano Ganesh that controls water pumps via to network with community members and
your project on Java.net and join-
provided an overview of the technology road- mobile phone, a boon for Indian farmers share their expertise. Watch them talk about
ing the Java Tools Community.
map for Java, including plans for Java SE 8, so they dont have to walk to their pumps their JUGs and the challenges they face.

05
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java nation /

COMMUNITY
JDK FOR MAC OS X
AVAILABLE

JAVA IN ACTION
Oracle has released its
first Java Development
Kit (JDK) and JavaFX
Software Development
Kit (SDK) for Mac OS X.
Java developers can now download
Java Platform, Standard Edition 7,
Update 4 (Java SE 7 Update 4) and

JAVA TECH
JavaFX SDK 2.1 for Mac OS X from
Oracle Technology Network. The Java
SE 7 Update 4 SDK includes the next-
generation Garbage Collection algo-
rithm, Garbage First (G1), which has
JAVA USER GROUP PROFILE

Silicon Valley JUG


been highly anticipated by the Java
developer community.
Mountain View, California JavaFX 2.1 introduces playback

ABOUT US
support for digital media stored in
WHEN THE SILICON VALLEY WEB DEVELOPER JAVA USER Even the attendees have been known to give presen- At a Silicon Valley the MPEG-4 multimedia container
GROUP WAS FORMED in April 2003 by Van Riper, its initial tations in a pinch. Once I made a scheduling mistake JUG meeting
format containing H.264/AVC video
focus was on the Jakarta Struts framework. In July 2004, and realized that our speaker was not scheduled to come in May, speaker
David Montag of and Advanced Audio Coding audio.
the focus was broadened to include J2EE. Today, the group until one month later, Nilson says. Luckily jQuery com-
Neo Technology It also includes WebView support for
covers all Java technologies and as of April 2012 is known mitters Jonathan Sharp and Mike Holster were in the
provided a high- JavaScript to Java method calls. We
as the Silicon Valley Java User Group (SVJUG). front row. At 6:55 p.m., I approached them about giving a level introduction to
Kevin Nilson joined Riper as coleader in 2007, when the talk at 7:00 p.m. Jonathan and Mike were happy to fill in look forward to delivering simultane-
graph databases.
group still had fewer than 100 members. Joining Meetup and gave a great presentation. ous releases of the JRE [Java runtime
in 2009 proved to be a turning point in growth. By August Marakana TechTV records many SVJUG talks, and when environment] across all major operat-
2009, the group had 536 members, which doubled to 1,071 the JUG cohosts a meeting with the Silicon Valley JavaFX ing systems later this year, so all Java
by May 2010. Current membership exceeds 2,300. Meetup, Marakana live-streams the event. Our group has users will be able to take advantage of
SVJUG meets on the third Wednesday of each month at been very lucky because others have stepped up to help the latest features and security fixes,
Google headquarters in Mountain View, California, with record our talks, notes Nilson. We do not do any of our says Hasan Rizvi, senior vice president
attendance ranging from 100 to 200 people. The JUGs own recording, so usually only popular talks get recorded. of Oracle Fusion Middleware and Java
location provides many advantages, Nilson says, especially SVJUG members also actively participate in the Silicon products at Oracle.
with regard to speakers. Some of the top speakers we have Valley Code Camp, a community event where developers blog
had are James Gosling, Joshua Bloch, Rod Johnson, Neal learn from fellow developers. All are welcome to attend and
Gafter, Bob Lee, Gavin King, Chet Haase, Romain Guy, and speakmore than 2,000 developers attended last year. ART BY I-HUA CHEN
the Java Posse. SVCC 2012 will be held October 67 (following JavaOne).

PHOTOGRAPHS COURTESY OF SILICON VALLEY JUG


06
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java nation /

COMMUNITY
JAVA AT

JAVA IN ACTION
MAKER FAIRE Oracle CEO
Larry Ellison
discussed the
Java came to life at the Maker Faire Bay Area 2012 ease of developing
(May 1920 in San Mateo, California). In the Java applications for
Zone in the Expo Hall, attendees explored storyboard- the cloud.
ing, 3-D animation building, device programming,
body motion sensors, game making, and more. They
Develop in the Cloud

JAVA TECH
learned how Java interacts with other devices using
a motion sensor and a Webcam, and how Microsoft At an Oracle cloud strategy Webcast on June 6, Oracle
Kinect records motion to animate a Java game. CEO Larry Ellison introduced Oracle Developer Cloud
Attendees also played Breakout using the PicoBoard, Services, a component of Oracle Cloud Platform Services.
an external circuit board with sensors for sound and Oracle Developer Cloud Services will provide instant
light, slider and button controllers, and four resistance access to tools that enable faster, smarter, and more-
sensors. They also had the opportunity to try out Alice, collaborative development in the cloud. With Developer

ABOUT US
a tool used to teach Java programming fundamentals Services, development teams can use their favorite tools
using 3-D graphics and a drag-and-drop interface; (Hudson for continuous integration, Git and GitHub for
source control, wiki and tasks for project management)
Greenfoot, a 2-D tool ideal for teaching Java program-
in the Oracle Cloud. Integration with popular IDEs such
ming basics in high schools and universities; and other
as Oracle JDeveloper, Eclipse, and NetBeans makes
tools for the twenty-first-century classroom.
Developer Services an excellent way to maximize produc-
The 2012 Maker Faire also offered several interesting
tivity and innovation.
presentations at center stage, including Gamification,
Robotics, and Simulators: How to Get Started with Java
Programming. This panel, targeted at students and
newbies, focused on why Java technology dominates
cutting-edge software development, and provided
ways to get started learning programming and Java. JavaSpotlight Podcast
Java Magazines Justin Kestelyn moderated the panel Listen to the JavaSpotlight podcast
of Oracle employees: Caron Newman, senior curricu- for interviews, news, and insight for
lum manager for Oracle Academy; Daniel Green, sys- and from Java developers. Hosted
tems engineer; Kevin Roebuck, solution specialist with by Roger Brinkley and Terrence Barr, blog
Oracles global education team; and Ultan OBroin, this weekly show includes a rotating
director of global user experience. They discussed why panel of all-star Java developers.
Future Java developers played games at the
Java is such a great tool for education. Java booth at Maker Faire Bay Area 2012.
PHOTOGRAPHS BY SAUL LEWIS
07
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java nation /

COMMUNITY
JAVA CHAMPION PROFILE
JORGE VARGAS

JITSI
FEATURED JAVA.NET PROJECT footprint from 160 x 120 pixels to 640
x 480 pixels; support for ZRTP and call
Java Champion Jorge Vargas, we shared different points

JAVA IN ACTION
encryption; and support for Extensible
freelance Java consultant, of view about our careers.
Messaging and Presence Protocol (XMPP)
blogger, and cofounder and Im thankful that my career
(enabling video calls using Google Talk,
CTO of the geolocalization- has permitted me to travel,
Gmail, and Android phones).
based application Yumbling, and especially to have close
The latest Jitsi releases have added the
talked about what he does contact with universities and
capability to establish conference calls in
when hes not working. their students.
situations where people are using different
Java Magazine: Has being
protocols; Domain Name System Security
Java Magazine: Where did a Java Champion changed
(DNSSEC) support; and additional hot-plug
you grow up? anything for you with respect

JAVA TECH
support for audio devices.
Vargas: In Mexico City. Now hard drive and 640 KB of to your daily life?
The development team is currently
Im living near there in a RAMa real monster! Vargas: When I became a Java
working on features to be released in the
small town named Calimaya. Java Magazine: What do you Champion, I felt I needed to
coming months, including the Jitsi Android
Java Magazine: When did you enjoy for fun and relaxation? expend more effort sharing
port and high-quality video conferencing.
first become interested in Vargas: Well, I enjoy pro- my experiences and knowl-
More than 100 developers have contrib-
computers? gramming for fun! I also play edge at universities, con-
Blue Jimp developers collaborate using uted to the Jitsi code base. Currently, more
Vargas: When I was 16, piano and enjoy looking at ferences, and workshops. I
Jitsi, an open source Java VoIP client. than 20 developers contribute new code
the stars. In school, I spent

ABOUT US
my friend Adolfo was very consider this a responsibility
and patches, and many users test snapshot
interested in computers, many fun months building of the role, because people
Over its nine-year history, Jitsi has evolved versions and report the issues they find.
so I started studying and my own telescope. ask me more questions, and
from a Session Initiation Protocol (SIP) According to Ohloh, the Jitsi code base
experimenting, too. My first Java Magazine: Whats a typi- value my judgment.
research project into a widely used open consists of more than 700,000 lines of
formal project was a Lotus cal family day? Java Magazine: What are you
source Java Voice over IP (VoIP) and instant source. About 50,000 users download the
1-2-3 application I wrote for Vargas: During the work looking forward to in the
messaging client that supports five full- application each month. The total user base
a building company that cal- week we talk, and I help coming years?
time developers working at Blue Jimp. for Jitsi (including all of its branded incar-
culated project costs. I wrote with homework if Im not Vargas: I want to expand my
According to Jitsi Project Lead Emil Ivov, nations) could approach 1 million people.
4,000 lines of code and was too busy. We enjoy going to career possibilities and also
SIP Communicator (Jitsis predecessor), FOSS [free and open source software] is
paid about US$300. the cinema and eating out. I study piano. Professionally,
released in 2003, did SIP calls, includ- a viable option for anyone setting up a new
Java Magazine: What was visit my parents to talk about Ill continue working on
ing video. In 2006, additional developers project, Ivov says. Business models that
your first computer and pro- plants, flowers, or politics, or Yumbling. And I want to write
joined the project. The entire code base was rely on selling licenses to end users simply
gramming language? to play cards or dominoes. for Java Magazine!
reworked, and Jitsi was born. In 2009, Ivov dont scale. With FOSS you get to concen-
Vargas: The first language I Java Magazine: What side
founded Blue Jimp, which offers customers trate on development, and you also gain
learned was Basic, along with effects of your career do you Read more about Jorge Vargas
professional support, maintenance, and valuable outside contributions.
macros in Lotus 1-2-3. Next, I enjoy the most? in An Interview with Java
custom development related to Jitsi. This article is the first in a series of Java
spent some years with Visual Vargas: I remember a deli- Champion Jorge Vargas. You
Several development milestones have .net project profiles. Want to have your
cious dinner in San Francisco
blog
Basic (3.x and 4.x). My first can also visit his blog and find
increased Jitsis user base over the years, project profiled in Java Magazine? Tell us
computer was a 286 running with other Java Champions; him on Twitter (@edivargas)
including the expansion of Jitsis video why its great.
MS-DOS 4.0, with a 100 MB it was wonderful because and Facebook.

08
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java nation /

COMMUNITY
AUGUST New England Software Symposium
JAVA OLYMPICS
QCon SEPTEMBER 1416 FINAL ROUND
AUGUST 45 BOSTON, MASSACHUSETTS
RESULTS
SO PAULO, BRAZIL

JAVA IN ACTION
QCon is an enterprise software Greater Atlanta Software
development conference designed Symposium
for team leads, architects, and proj- SEPTEMBER 2123
ect management and is organized ATLANTA, GEORGIA
by and for the community. Topics
include architecture, functional lan- SEPTEMBER
guages, mobile, agile engineering Web Developer Conference
practices, and more. The keynote (WDC) 2012

JAVA TECH
lineup includes Martin Fowler, chief SEPTEMBER 1718 The 20112012 Java Olympics
scientist at ThoughtWorks, and HAMBURG, GERMANY wrapped up on April 28 with a
Zach Holman, architect of GitHub. This conference for develop- dramatic final round at Kazakh-
ers of Web applications, content British Technical University in
The No Fluff Just Stuff Software and online managers, agencies, Almaty, Kazakhstan. Out of 1,573
Symposium Tour and Webmasters focuses on pro- students from 322 universities
Since 2001, the No Fluff Just Stuff fessional development of Web
who participated in Round One,
(NFJS) Software Symposium Tour applications.

EVENTS
only 21 advanced to Round Three,

ABOUT US
has delivered more than 275 events
the finals. Only three of these
with more than 40,000 attendees. onGameStart 2012
would take home a prize.
JavaOne 2012 SEPTEMBER 30OCTOBER 4, NFJS is known for knowledgeable SEPTEMBER 1921
After a grueling four hours of
SAN FRANCISCO, CALIFORNIA speakers and timely presentations WARSAW, POLAND
that cover the latest trends within At the self-dubbed first HTML5 testing in which the contestants
the Java ecosystem and agility game conference, speakers include had to solve five problems, Igor
Java continues to move forward. Experts from the
space. Upcoming symposium dates Andres Pagella, Jerome Etienne, Ignatiev (above left), a student
worldwide Java community will share unique and
include the following: Jon Howard, Jonas Wagner, Jordan at Chelyabinsk State University
leading-edge content with attendees at JavaOne 2012.
Mechner, and many others. in Russia, won first place. He had
Tracks range from the stronger-than-ever core Java
Research Triangle Software correctly solved four of the five
platform and advancements in tools and techniques Symposium The Developers Conference 2012 questions in the first 90 minutes
that make it easier to write better code in less time to AUGUST 2426 SEPTEMBER 2829 of the competition and appeared
the application development languages that utilize the RALEIGH, NORTH CAROLINA FLORIANPOLIS, BRAZIL to have the contest locked up. But
power of the Java Virtual Machine, including Groovy, One of Brazils largest developer he struggled with the last ques-
JavaScript, JRuby, Kotlin, and Scala. Dont miss it! Pacific Northwest Software conferences, with locations in So tion while the rest of the field
Symposium Paulo, Florianpolis, and Goinia, advanced on him. In the end,
SEPTEMBER 79 The Developers Conference offers
Ignatiev prevailed. Peter Pchelko blog
SEATTLE, WASHINGTON dozens of tracks, several of which
and Andrey Misnik finished sec-
are Java related, to more than
ond and third, respectively.
6,000 attendees.

09
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java nation /

COMMUNITY
JAVA BOOKS

SINGING JAVAS

JAVA IN ACTION
PRAISES
The community spirit Zoran Severac
experienced at JavaOne 2011 was the
inspiration behind his smash hit (more JAVA EE 6 COOKBOOK FOR JAVA APPLICATION BEGINNING JAVA 7 JAVA 7 RECIPES: A PROBLEM-
than 5,000 views on YouTube) Java SECURING, TUNING, AND ARCHITECTURE: By Jeff Friesen SOLUTION APPROACH
People. The song itself is free and EXTENDING ENTERPRISE MODULARITY PATTERNS Apress (November 2011) By Josh Juneau, Carl Dea, Freddy

JAVA TECH
open source. You can listen to it, play APPLICATIONS WITH EXAMPLES USING OSGI Guime, and John OConner
Jeff Friesens Beginning
it, modify it, and use it for commercial By Mick Knutson By Kirk Knoernschild Apress (January 2012)
Java 7 gets you coding with
and noncommercial purposes for free Packt Publishing (May 2012) Prentice Hall Professional
the new Java 7, Oracles lat- This book offers solutions
as long as you put some reference to the (March 2012)
Java EE is a widely used est release of the popular to common programming
original song, says Severac. platform for enterprise server Over the past several years, problems you may have
Java language and platform.
Java People and its community programming in the Java pro- module frameworks have encountered while develop-
It is the definitive guide to
concept impressed so many of us here gramming language, and this been gaining traction on ing Java-based applications.
the Java language and the

ABOUT US
at Java Magazine that were opening book covers recipes on secur- the Java platform. Java Updated to cover the new-
numerous APIs that youll
a general Java Nation call for songs. If ing, tuning, and extending Application Architecture lays est features and techniques,
need to master to become
youre a songwriter who, like Severac, enterprise applications using the foundation youll need to Java 7 Recipes provides code
an accomplished Java devel-
appreciates Java and the Java commu- a Java EE 6 implementation. incorporate modular design examples involving Servlets,
oper. The book begins with
nity, start composing! Send us links to It begins with the essential thinking into your develop- JavaFX 2.0, XML, Swing, and
an introduction to Java and
your Java Nation anthem. changes in Java EE 6 and ment initiatives. Before he more. This book uses the
focuses on fundamental
dives into the implementa- walks you through 18 patterns concepts of the Java language popular problem-solution
tion of some of the new fea- that will help you architect such as comments, identi- format: you can look up
tures of the Java Persistence modular software, author fiers, variables, expressions, the specific programming
API (JPA) 2.0 specification. Kirk Knoernschild lays a solid and statements. Other topics problem you want to solve,
There are several additional foundation that shows you in the book include classes read the solution, and apply
sections that describe some why modularity is a critical and objects, advanced lan- that solution directly in your
of the subtle issues encoun- weapon in your arsenal of guage features, language own code. The authors focus
tered, tips, and extension design tools. Throughout, APIs, collecting objects, and on problems and solutions
points for starting your own youll find examples that much more. rather than on the Java pro-
JPA application, or extending illustrate the concepts. gramming language itself. blog
Watch Zoran Severac perform his ode to an existing application.
the Java community, Java People.

10
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
JCP Executive Series

A Conversation

JAVA IN ACTION
with Gil Tene
Azul Systems CTO Gil Tene discusses the state of Java and the JCP.
BY JANICE J. HEISS

I
n the first of a series of Java Magazine: Tell us a little about your day job.

JAVA TECH
interviews with distin- Tene: Im the CTO of Azul Systems, and at Azul
guished members of the we focus on building highly scalable JVMs. So our
Executive Committee of the world is Java and only Java, which is why the JCP
Java Community Process (JCP), and the Java community are central to everything
we sat down with Azul Systems we do. Over the years, weve delivered massively
CTO and Cofounder Gil Tene, scalable JVMs that can run on platforms with
who represents Azul on the JCP, anywhere from a couple to almost a thousand

ABOUT US
to get his take on how things CPU cores, and a handful to hundreds and thou-
are going with Java and the JCP. sands of gigabytes of memory. Were probably
Azul Systems, a builder of highly best known for our very concurrent garbage col-
scalable Java Virtual Machines lection and the effective elimination of garbage
(JVMs), has been a JCP member collection pauses as an issue for response-time-
since 2003 and a member of sensitive enterprise Java applications.
the Executive Committee since I mix both hands-on engineering, where I
November 2011. work within and with the teams at Azul, and a
lot of external activity involving conferences and
papers and customer interaction. Ive been doing
this at Azul for about 10 years, and its the most
fun that Ive ever had at a job. Azul is like a toy
store for engineers. Ive specifically worked on
various parts of scalable JVMs, including every-
Gil Tene, CTO of Azul Systems,
prepares for a Webcast at thing from concurrent garbage collectors to
company headquarters in locking and transactional memory. Weve always blog
Sunnyvale, California. had the approach of doing whatever it takes
for runtime scalability. Ive built kernel code and
advanced virtual memory management code,
PHOTOGRAPHY BY MARGOT HARTFORD

11
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
ON INNOVATION
The JCP is certainly
designed new processor features a place to have That requires participation at think that staying within the scope that the
and instructions, and played a
lot with virtualization.
innovation happen. . . . all levels from JCP members
from executive participation
JCP, as a standards and community body, is
able to credibly work and be productive in
For the last couple of years,
But we should focus shaping process, rules, and is very important. You may have seen the
that innovation on

JAVA IN ACTION
Azul has focused more on governance; from expert groups recent discussions about the Social Media
software-centric products, so the parts that are in standardization efforts; all API, JSR 357, which was about the need for a
the future trajectory of the Java
platform has become increas-
under our control and the way to people developing
code and contributing in differ-
standard Social Media API for Java that the
Executive Committee rejected in an 8-to-5
ingly more important to us.
within the purview ent ways. We dont want to see vote. We took a position against it. I think
We want to contribute to the of what the JCP is Java become a single-company the JCP should innovate in areas that are
leadership of the JCP, rather intended to do. platform, which means the under its control and scope, and when it can
than just being followers. Weve community has to contribute to assemble credible expert groups that lead
been moving closer and closer the leadership. the industry in the subject matter involved.

JAVA TECH
to the leading edge with Java. As Java Magazine: How should the But I also think the JCP should not attempt to
our software is now consumed by more and JCP walk the fine line between encouraging innovate outside of those boundaries. Having
more people, developers want to interact innovation and creating stable standards? the JCP try to standardize things that extend
with it more. While we support a lot of Java Tene: The two are not necessarily contradic- far beyond the Java platform and that are in
EE activity, our technical focus is on Java SE, tory, but sometimes they are. Personally, I a state of flux is, in my opinion, fundamen-
where we hold the most expertise.
Java Magazine: What are your main concerns

ABOUT US
about the JCP?
Tene: Weve been members of the JCP for
about nine years. We joined the Executive
Committee in 2011 in an effort to become
more active in the process. Like the rest of the
community, we had concerns about the shifts
in the platform that might occur with Oracles
acquisition of Sun, so rather than sit on the
sidelines and watch it happen, we decided to
actively participate. Our concern is to make
sure that the JCP is not dominated by a single
company and that the JCP is not just a rubber
stamp for Oraclesomething that I believe
Oracle does not want to have happen either.

blog
Tene and members of Azuls
engineering team discuss
a current project. All team
members receive a white lab
coat after four years at Azul.
12
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
tally wrong, and will just result in a standard opinion, our best shot at maintaining and
nobody uses. increasing community participation while
The JCP is there to move the Java platform doing the job the JCP is meant to do.
forward, but in areas where industry efforts Java Magazine: What are some key issues that

JAVA IN ACTION
already exist to stabilize, model, and stan- the JCP needs to address?
dardize behavior, the JCPs role is to follow Tene: There are clarification issues related to
and not to lead. Imagine the JCP trying to licensing, IP accessibility, and transparency
standardize XML while in flux and before that have been a concern for many people.
the W3C decided what the standards should The JCP has taken some good steps in the
look like. The JCP is not the right Executive Committee, and
place to standardize those, but ON COMMUNITY the JCP.next effort has begun
its certainly the right place to Tying into community addressing transparency and
incorporate external standards
development and other process rules specifi-

JAVA TECH
with APIs for Java. cally with JSR 348. This leads to
Java Magazine: How can we innovation efforts and greater transparency in working
increase community participa- helping them naturally groups. Its a good first step,
tion in the JCP? flow through the but there are future second and
Tene: There are many ideas
flying around. I think the JCP is
JCPs process is, in my third steps required in the JCP
.next process. Some of these are
certainly a place to have innova- opinion, our best shot structural and procedural, while

ABOUT US
tion happennobody else will at maintaining and some are more fundamental
innovate in the Java platform increasing community and about clarifying issues
for us. But we should focus that
innovation on the parts that are
participation while around accessibility of the actual
implementations of the TCKs
under our control and within doing the job the JCP [technology compatibility kits],
the purview of what the JCP is is meant to do. what the rules are, and what
intended to do. For example, spec leads will do in order to
if we want a future version of provide access. This is dangerous
Java SE to have certain features territory because there are a lot
with new syntax or new capabilities or APIs, of very strong opinions.
or define new ways for containers to work in On the one hand, we have people who
the Java EE space, the JCP is the only place want to force the whole thing to be open
to standardize that. We can prototype it and sourced. I, for one, dont believe thats a
Tene and an Azul engineer brainstorm while working work within Java.net and within open source viable path, and I think that an environment
with magnetic building tools. communities and play with implementations, that allows solutions to take any form is the
but as far as defining the Java platform and right way for a standard to work. Whether an blog
its features, the JCP is it. implementation is proprietary, for profit, and
So tying into community development and highly controlled, or open source and free, we
innovation efforts and helping them natu- should be able to implement and adhere to
rally flow through the JCPs process is, in my the same standards.
13
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
Tene chats with a JSR 348, but the JSPA in some cases allows
member of Azuls and sometimes even requires expert group
engineering team. members to maintain levels of confidential-
ity around work that is material to a JSR. This

JAVA IN ACTION
sort of contradiction can potentially bring JSR
work to a halt if we do not resolve it through
Tene: I would say that Oracle is in the process rule changes and the JCP.next efforts.
of delivering. I wouldnt say it has delivered. Java Magazine: Do you think theres a percep-
We see a lot of promise and very good inten- tion in the IT community that Java is aging
tions, but its still too early to say that we see or that some other language or platform will
actual results. As part of the community, replace it soon?
we look at this as something we continu- Tene: Yes, I think that there is a perception
ously have to watch. Part of our role in the that Java is aging. Theres a lot of talk about it

JAVA TECH
Executive Committee is to be that external, slowing in innovation. The interesting thing is
non-Oracle watchful eye that points out that one usually hears this sort of thing in the
ON FOLLOWING when were heading in the wrong direction. context of some new technology that is actu-
The JCP is there Lets be specific. We certainly have seen
the JCP deliver on JSR 348 and improved rules
ally overtaking and replacing an older plat-
form. But I think that this is not the case with
to move the Java and improved transparency so that commu- the Java platform. The Java platform has been
platform forward, nity efforts will match what the community around for 17 years and has been enormously

ABOUT US
but in areas where wants. But the process is only about half successful. Two or three years after Java first
industry efforts done. We still have more work to do in rela-
tion to things like the JSPA [Java Specification
emerged, it was already clear that it was dis-
placing other development and deployment
already exist to So I dont think that the JCP should be dic- Participation Agreement] document that will platforms. I dont currently see some other
stabilize, model, tating specific license terms or saying specifi- be addressed in a future JSR. emerging platform that is threatening Java
and standardize cally that certain licenses are allowed or not. The specific areas that we are concerned like Java threatened other platforms. There
behavior, the JCPs But I do think that some guidelines and some
boundaries are needed. For example, reliable
with are in-flux situations where the new
rules that weve put in place actually contra-
are many interesting new developments in
dynamic and functional languages, rapid
role is to follow and and lasting access to TCKs under a known, dict the previous way weve been working. development techniques, and other inno-
not to lead. predictable set of terms is a fundamental So things that were fine a year ago under the vations that are not necessarily in the Java
need for companies, projects, and individu- previous process are now in contradiction language, but the vast majority of those tend
als to invest in implementing and following with the new rules. And some of that has to target and run on the Java platform rather
a standard under the JCP. We should clearly not yet been resolved. New rules that control than threatening it. </article>
and strongly define the minimal require- what we can or cant do can stand in the way
ments that JSRs should meet for providing of doing work that we were previously able
such access. Weve seen over the last few to do. For example, including confidential Janice J. Heiss is the Java acquisitions editor at blog
years a lot of stagnation. information in the materials discussed and Oracle and a technology editor at Java Magazine.
Java Magazine: Has Oracle delivered on the worked on by JSR expert groups stands, in my
promise of increased transparency and open- opinion, in contradiction with the transpar- LEARN MORE
ness in the JCP? ency rules and requirements of JCP 2.8 and Java Community Process
14
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
Data Quality Tools for Java
BEFORE
Telephone Verification Name Parsing & Genderizing
john smith iii phd
melissa data corp.
Geocoding 22382 Empresa 92688
7145895200
john@800miAL.con
Address Verification &
Standardization
AFTER
Melissa Data Corp.
Email Address Verification John Smith III PhD
22382 Avenida Empresa Ste 100
Rancho Santa Margarita, CA 92688-2112
949-589-5200
John@melissadata.com
Delivery Indicator: Business
*Highlights indicate added and/or corrected data.

Realtime NCOALink
Change-of-Address
Web Services & APIs Web Service
available
Duplicate Elimination

Now, finding the right data verification tools doesnt have to be so puzzling. Global address verification for 240 countries
Melissa Data offers customizable APIs, Web services and enterprise appli- Clean and validate data at point-of-entry or in batch
cations to match your budget and business needs. For solutions to cleanse, Correct misspellings, missing directionals, and confirm deliverability
validate and standardize your contact data, were ready to help you find the Enhance addresses with County, Census, FIPS, etc.
perfect fit. Append rooftop lat/long coordinates to street addresses
Update records with USPS and Canadian change of address info

Request free trials at


MelissaData.com/myjava or call 1-800-MELISSA
COMMUNITY
Building a Better Spreadsheet

JAVA IN ACTION
Java powers analytic breakthroughs
at QuantCell Research.
BY DAVID BAUM

JAVA TECH
I
(Left to f you want to change the world, you need
right) Agust to start with a mission that everybody
Egilsson, Kris can understand. Similarly, if you want
Thorleifsson, to change the face of analytics, you need a
and Bjorn
simple paradigm that people can quickly
Jonsson at

ABOUT US
QuantCell comprehend. You dont invent a new pro-
Research gramming language or craft a radical user
headquarters interface; instead, you leverage the existing
in Reykjavik, productivity tools that people know and love.
Iceland It was precisely this philosophy that moti-
vated Agust Egilsson to develop QuantCell, a
software environment for constructing visu-
ally rich models and big data analytics and
applications. Rather than devising a new pro-
gramming motif, Egilsson adopted one that
animates businesses everywhere: the familiar
spreadsheet interface. And instead of writing
a new integrated development environment,
he appropriated Java, the most versatile
programming language of the modern age.
The result is a powerful end-user environ- blog
ment that lets researchers, analysts, domain
experts, and developers analyze any type of
data in a fast, compelling way.

PHOTOGRAPHY BY THORSTEN HENN


16
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
Thorleifsson and Egilsson division, we work with fund managers to
discuss QuantCell capabilities analyze their portfolios and make recom-
with a team member. mendations, Grazi explains. Our valuations
yield thousands of variables, including statis-

JAVA IN ACTION
tics about a companys financial statements,
Rice University, Thorleifsson projections, and ROI.
had served as CMO of the Typically a programmer must sit down with
Dohop.com travel search engine an analyst to plug all these variables into a
and held senior management custom program, but Grazi says QuantCell
positions in the financial ser- allows people with very little programming
vices industry before sign- experience to achieve the same results within
ing on with Egilsson to found an intuitive spreadsheet environment.
QuantCell Research. You can include libraries in the QuantCell

JAVA TECH
The pair had big ideas and spreadsheet and link cells to generate a tre-
an even bigger goal: to build a mendous amount of statistics, Grazi explains.
better risk-analysis system fol- All of a sudden an analyst becomes a pro-
lowing the near collapse of the grammer. We have our own visualization and
global financial industry. As the charting routines that users can access just by
principal author and developer double-clicking on a cell. Its very convenient.
of the QuantCell environment,

ABOUT US
SNAPSHOT Observing quantitative analysts in the Egilsson had already been working with a pro- A FLEXIBLE FOUNDATION
QUANTCELL financial services industry, it was clear that totype of the QuantCell system, both in invest- By basing their solution on Java, QuantCells
RESEARCH people preferred to use spreadsheets for ment banking and academia. Now he set his founders gained instant support from an
quantcell.com everything that they could, Egilsson explains. sights on one of the holy grails of computing: extremely large, well-informed, and gener-
Headquarters: So we set out to build an analytics and data a programming environment ous developer community
Reykjavik, Iceland visualization environment that preserves the that would allow nondevelop- YEARS OF RESEARCH aggregating a huge portion
benefits of the spreadsheet, such as short ers to create powerful models of the worlds quantitative
Industry:
Technology turnaround times, and addresses all of its and applications on par with
We are opening the knowledge into their user-
Java version used: shortcomings, such as the need to rely on the those created by IT experts. door for nondevelopers friendly environment. Thanks
Java SE 7 IT department for advanced functionality. Victor Grazi, a vice president to take advantage of to the rich and ever-evolving
Its an area that Egilsson knows well. After
receiving his doctoral degree in mathematics
at Credit Suisse in New York,
New York, has been testing
many years of research Java ecosystem, hundreds
of thousands of algorithms,
from the University of California at Berkeley, an alpha version of QuantCell and Java coding by processes, and methods are
he delved into quantitative research and risk as a potential way to simplify some of the worlds available for use with the
management for financial services institutions
and biotechnology firms. He was soon joined
corporate valuation exer-
cises. Grazi has been a Java
best researchers and QuantCell system.
QuantCell can execute Java blog
in this endeavor by Kris Thorleifsson, a former developer since 1995 and has institutions. code snippets within spread-
Java product manager at Sun Microsystems worked in the financial indus- Agust Egilsson, Cofounder, sheet cells, either entered
with a background in cloud computing. After try since 2000. QuantCell Research directly by the user or created
earning his MBA from Houston, Texasbased In the Credit Suisse Holt using end-user formula wiz-
17
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
search for data and make that data available functions to return objects to the cells, select-
for further analysis with one click. ing components from a knowledgebase of
The QuantCell environment creates Java externally and internally created Java libraries.
classes or Java archive (JAR) files that can For example, the company is creating a com-

JAVA IN ACTION
be deployed directly into any Java produc- ponent browser to access pricing components
tion system or are deployed automatically for complex financial products and derivatives
to cloud computing infrastructures such as such as algorithms, payoffs, and simulation
Apache Hadoop. Unlike the lock-in typical components. Advanced users can develop
with other systems, QuantCell models are and deploy Java solutions as Web services as
independent of the environment and sup- they create computationally intense projects
port open standards. They can also connect requiring access to various datasources, algo-
to their own private relational databases or rithms, and computational clouds.
semistructured datasources. Models and apps built in QuantCell are

JAVA TECH
pure Java APIs that can be deployed into exist-
HOW IT WORKS ing Java-based production systems or as Web
Novice users interact with QuantCell much services, explains Egilsson. They run on the
like an online spreadsheet application, using Java virtual engine and are therefore easily
UI wizards that generate Java, SQL, Python, or deployed into existing production systems as
R-like expressions in conjunction with a rich a Web service. Some of our early adopters are
knowledgebase of methods. The expressions particularly excited about the ability to deploy

ABOUT US
in turn create Java objects in the spreadsheet custom MapReduce algorithms directly to
cells such as mappers, reducers, tables, Hadoop cloud installations from the spread-
databases, images, multimedia, data cubes, sheet interface.
compute clouds, and Java classes. Users visu-
alize the objects via various UI controls such ENRICHING THE BREW
as charts and graphs, a table frame control, a QuantCell inherits its visual character-
database browser, a data cube viewer, a 3-D istic from JavaFX. Egilsson says he and
protein image viewer, a chemical structure Thorleifsson decided to use JavaFX because
visualization control, a spatial image control, it lets people easily access existing Java APIs
and many other specialized components. and because of its support for rich graphics,
We didnt initially understand what animations, and effects. JavaFX is instru-
Egilsson and ards, says Thorleifsson. The code is assem- QuantCell was, but as soon as we figured out mental in bringing rich visualization meth-
Thorleifsson catch up bled, tested, and compiled one expression at that the cell is actually the variable that con- ods to the spreadsheet, he says. Its also
on company business a time, improving quality, shortening devel- tains the object, we began to see its poten- universal, since it runs on the worlds most
outside of QuantCell
opment time, and alleviating user-interface tial, Grazi notes. You can put any Java object widely used operating systems and supports
Research headquarters.
design chores. into a spreadsheet cell and then refer to that all the major browsers. blog
QuantCell also enables direct access object through another cell. To do something In addition, JavaFX takes advantage of the
to some of the worlds most important similar in another analytic environment is computational power available locally on
data providers, such as Thomson Reuters, much more complex. each users machine, and each user can run
Bloomberg, and Xigniteallowing people to Experienced users can write their own complex computations locally in the Java
18
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
Virtual Machine (JVM) instead of relying on flexibility, saying researchers can stop in the available libraries and the Java Community
remote servers. For instance, users can view middle of a program, run other programs, and Process will keep this community thriving for
a 3-D image of a protein or an oil field, which manipulate the data any way they like. He has a long time.
would be less robust if the application were been testing an alpha version of QuantCell to Its already a thriving ecosystem, fed largely

JAVA IN ACTION
only server-based. JavaFX delivers the per- see if it can fulfill this same role in a Java envi- by Java experts at universities and open source
formance we need and provides excellent UI ronment. So far, he likes what he sees. communities, which continue to contribute
controls right out of the box, Egilsson adds. Productizing something created in advanced analytic libraries. Popular examples
MATLAB is not a trivial process, but QuantCell include artificial intelligence and machine
INDUSTRY APPLICATIONS will make the deployment more convenient, learning (Apache Mahout, Java-ML, and
QuantCell Research is initially marketing its Sigurjonsson explains. For example, in one Weka), biotechnology (BioJava), and financial
solution to finance professionals immersed in cell you can get the data; in the next several mathematics (jQuantLib). Unfortunately,
portfolio and risk analysis, because the solu- cells you can analyze it; and then you can pull most of these libraries are not immediately
tion lets those users take advantage of existing in off-the-shelf statistical pack- usable by biotech researchers,

JAVA TECH
Java-based quant librariesalong with other ages, libraries, and visualization BRIGHT FUTURE financial analysts, and other
Java-based libraries, such as the MapReduce
framework for big data analytics. This versatile
tools. You can develop an algo-
rithm and deploy a JAR file right
It is early on, but domain specialists, who must
depend on skilled programmers
architecture lets them easily build advanced out of the system, so you have a we are excited to build custom applications for
models and financial products faster and deployed version that is ready for about QuantCells each analytical project.
cheaper, and with less reliance on IT. testing. I think it can save signifi- QuantCell changes all that.
The company is also expanding into the cant amounts of time in produc- potential. All Java APIs, libraries, and tools
Agust Egilsson

ABOUT US
talks with author life sciences industry, where alpha and beta tizationperhaps as much as 60 Victor Grazi, Vice work with QuantCell right out of
David Baum about users have found QuantCell ideal for analyz- or 70 percent. President, Credit Suisse the box. End users can call upon
QuantCell. ing genetic sequences, proteins, and markers. QuantCell also supports long- these libraries just by adding
QuantCells spreadsheet-based environ- running concurrent operations, them to the classpath, expand-
ment is a convenient way to engage non- allowing researchers to continue ing QuantCells existing catalog
experts in complex analytical research, says to work in a spreadsheet while the system of libraries, algorithms, and methods.
Dr. Styrmir Sigurjonsson, a senior statistician crunches data from either a local database or Applications and APIs created in NetBeans
at Natera, a life science company based in a remote cloud. or Eclipse can be moved into the QuantCell
Redwood City, California, involved in prenatal environment for further work or testing, and
genetic testing. A statistician can develop COMMUNITY SUPPORT those assembled in QuantCell can be moved
algorithms based on lab data and then pass As QuantCell gains momentum in anticipa- into NetBeans for further development.
the QuantCell spreadsheet back to the lab tion of a production release later in 2012, the In short, QuantCell finds itself at the inter-
researcher to continue the analysis. You can company is banking on continued support section of usability and functionality as it
get to a whole new level of complexity with- from the Java community to deliver a large and helps people of all skill levels take advantage
out having to bog down the researchers with robust ecosystem of computational solutions. of these rich analytic libraries on the one
that complexity. We decided to use Java in large part due hand, and advanced data visualization tools blog
Natera currently uses MATLAB, a popular to the dynamic nature of Java compilation, on the other. </article>
numerical computing environment and pro- lazy class loading, concurrency in Java, and
gramming language, to develop its prenatal optimization in the VM such as just-in-time David Baum is a freelance business, technology, and
testing products. Sigurjonsson likes MATLABs compilation, says Thorleifsson. The many lifestyle writer in Santa Barbara, California.
19
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
JAVA IN ACTION
For online travel leader priceline.com,
Java provides the maximum connectivity,
flexibility, performance, and portability.

JAVA TECH
BY PHILIP J. GILL

Direct
Connection

ABOUT US
M
aking online travel reservations seems
straightforward enough: The prospec-
tive traveler enters a desired itinerary
and is typically presented with a screenful of
options, including choices, prices, photos, and
moreall in a matter of seconds. From these
options, the traveler makes a decision. Simple
enough, right?

blog

PHOTOGRAPHY BY CATHERINE GIBBONS


20
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
SNAPSHOT For online travel sites, how-
ever, that up-front simplicity
PRICELINE.COM
priceline.com
belies the complexity behind
the screen. At priceline.com,
Headquarters:

JAVA IN ACTION
Norwalk, Connecticut
for example, a simple query
Industry: sets off a complex series of
Online travel services hundreds of interactions and
Revenue: connections to multiple hotel,
US$4.36 billion in 2011 airline, and other reservation
Employees: systems around the world,
350 in the priceline.com explains Michael Diliberto, CIO
business unit, 3,400
for the North America division
worldwide
of the Norwalk, Connecticut

JAVA TECH
Java version used:
JDK 6 and JDK 7 based firm.
We work with thousands
of suppliers and affiliates over
multiple distribution plat-
forms, says Diliberto. We
need to connect our system to
the appropriate supply inven-

ABOUT US
tory, so that means direct
connections to rental car
companies such as Hertz, Avis,
Alamoand to large global
distribution systems [GDSs]
such as Travelport or even a
smaller new GDS such as Farelogix, to get so easy in near real time is Java. For us, Java Priceline CIO Michael Diliberto (left)
access to the freshest inventory for hotels, has become a way of life, says Diliberto. and Vice President of Engineering
rental cars, and airline seats. Java provides us the ability to connect with Amit Poddar discuss project status
A search for hotel deals in New York other travel resources around the world more in front of the companys analytics
dashboards.
City can generate up to 500 simultaneous effectively and efficiently.
requests to suppliers systems, Diliberto
adds. Multiply that by thousands of custom- BEHIND THE SCREENS
ers querying the system simultaneously, and Priceline.com, the online travel business that
its easy to see that the core of priceline made Name Your Own Price famous, is one
.coms business is its ability to manage the of the worlds leading online travel services, blog
complex matrix of connections between offering everything from hotel rooms to
priceline.coms customers and suppliers. airline tickets, rental cars, vacation packages,
And the secret to making those connections and even cruises. It was founded in 1997 and
work so seamlessly and to making it all look a year later launched its travel services with
21
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
NOT SO SIMPLE

the help of celebrity pitchman A single user query According to Diliberto, years, but priceline.com had a change of
William Shatner. on priceline.com Java was ideal for the back- heart in 2000.
In the late 1990s, there were can generate up to end inventory search engines We realized that having a different tech-
a number of technologies because of its exceptional con- nology platform for front end and back
500 simultaneous

JAVA IN ACTION
available for building dynamic, nectivity and multithreading end was not the way to go, explains Amit
interactive Websites. These requests to suppliers. capabilities. Poddar, vice president of engineering at
included Java as well as Perl, Right from the very begin- priceline.com. We needed to consolidate on
PHP, and Microsofts COM ning, our back-end com- one platform to avoid unnecessary overhead
and Active Server Pages (ASP). munications to our suppliers of data transformations and to utilize our tal-
Although Java was less matureit had only has been designed and developed on a Java ent pool more effectively.
been introduced in 1995than the others, platform, says Diliberto. Java supports a The priceline.com team evaluated mul-
Diliberto saw great potential in the language variety of different communication protocols tiple enterprise platforms for performance,
and the development platform, not the least to interface with suppliers, so that we can go interoperability, and availability of tools and

JAVA TECH
of which was its promise of portability and where the data isin our case, connecting to programmers. Java was a clear winner. Since
vendor independence. In the end, the com- GDSs, airlines, hotel partners, and chainsto then, all major enhancements to the price-
pany chose a three-tier design: Java at the get the freshest inventory at the best price. line.com Website have been coded in Java.
back end, Oracle for database management, The combination of Java and Microsoft
and COM and ASP at the front end. technologies worked fine for the first few SEARCH SMARTER, NOT HARDER
Over the years, priceline.com grew from its
travel bidding model into a full-service online

ABOUT US
For Diliberto and travel company that includes published price
Poddar, Java was and Name Your Own Price travel services.
the answer to Priceline.com is the only travel site on the
consolidation needs internet to offer both options for travelers,
at priceline.com. notes Diliberto.
To present various travel options to their
consumers in real time, priceline.com devel-
oped a proprietary smart search system
using Javas multithreading framework. The
system acts like an inventory switch, says
Poddar. On one side are our customers,
including Priceline-owned Websites, affili-
ates, search engines such as Google, and
more recently mobile phones and tablets
such as iPad, he continues. On the other
side are hotels, airlines, car rental compa- blog
nies, and GDSs such as Travelport, Sabre, and
Pegasus, as well as startups like Farelogix.
When a customer is searching for the best
hotel deals on priceline.com, says Poddar,
22
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
Oracle and Java: Priceline.com has
been committed
A Good Marriage
behind the scenes the eral presentation mechanisms. GREAT MIGRATION Over the years, as priceline
to both Oracle priceline.com smart We could send the response .coms needs have changed, Java
and Java tech- search concurrently as a JSON object consumed by Priceline.com has also enabled the company
nologies since the
Website was launched; indeed, today the sites core
fetches data from Pricelines app on a customers has migrated its to migrate its IT infrastructure

JAVA IN ACTION
production transactional database is a 2 TB Oracle
various suppliers in
real time, sorts and
iPad, or ship it in XML format to
one of Pricelines affiliates.
Java applications across three different hardware
architectures and three dif-
database, and it also maintains a 17 TB Oracle data
warehouse. In total, the Norwalk, Connecticutbased filters the combined For this reason, adds Poddar, across three ferent operating systems with
online travel agency has 96 unique instances of data, and presents the Java turns out to be the perfect different hardware little effort, Poddar adds. The
best options to the technology for a flexible inven- company launched in 1998 run-
Oracle Database in its IT shop, a configuration that
provides both high performance and high availability. customer. tory switch.
architectures and ning on a Digital Equipment
Thats why Michael Diliberto, the companys CIO, Its very important three different Corporation AlphaServer with
North America, sees Oracles acquisition of Sun and
its Java technologies as a good deal for both Java
that the inventory
we are presenting is
VENDOR INDEPENDENCE
Vendor independence was a key
operating systems. Windows NT, then migrated to
SPARCbased servers running

JAVA TECH
users and the future of the platform. fresh, Poddar adds, criterion when selecting tech- Solaris (now Oracle Solaris), and
From the beginning, Oracle was committed to because theres a lot nology as well, and thats where today operates on an array of HP
the internet as a business platform, says Diliberto. of competition in the competing technologies fell Intelbased blade servers run-
[Oracle CEO] Larry Ellison saw the power of the online travel space, short. Instead of building a specific product, ning 64-bit Red Hat Linux.
internet and knew it was going to be a major piece and if a customer finds Java defines a specification and lets multiple Java has enabled us to move from one
of the economy going forward, and he wanted to
that our inventories vendors in the industry provide an imple- hardware platform to another quite eas-
prepare for it. And from a database standpoint, there
are stale, theyll go to mentation. This gives choice to customers, ily, says Poddar. We didnt have to involve
was always a solid commitment to creating the big-

ABOUT US
another travel site and says Poddar. any of the Java programming teams for the
gest, best-performing, and most scalable database
there could be. book there. From the start, priceline.coms back-end migration. It was completely done by the
Weve always been big fans of Java as a technol- Not all suppliers database has been an Oracle database. support staff.
ogy but had always been a little bit concerned about have the same inter- But back in 2000, Oracle didnt have what Another important benefit is that Java is
its survival, Diliberto continues. With Oracle having face, Poddar explains, priceline.com considered a viable Java driver open source. Priceline.com is committed to
a solid track record of turning products into profit, but Java supports a for that database. We started using driv- open source technology wherever and when-
weve been encouraged that Oracles leadership sees vast array of data for- ers from one company, says Poddar. The ever possible as a way to maintain vendor
a future in Java and is willing to invest in it and drive mats, transformation performance was OK, but we didnt really independence, explains Diliberto.
it forward, to keep it alive and to keep it growing. The tools, and communica- like it, so we moved to a second company. Besides Java, the companys IT infrastruc-
company has proven that over the last two years. tion protocols. Eventually Oracle came out with their own ture uses the Apache Tomcat Web server
Were very happy with the continued investment With Java we can drivers and we moved to them. and the Linux operating system. Going
that Oracle has been making in the Java platform. easily receive data We were able to successfully replace one with open source technologies such as Java
from suppliers either implementation of the driver with another as much as possible puts us in a good posi-
in SOAP wrapped XML without modifying a single line of code, tion, says Diliberto. We feel that it gives us
using HTTPS or in structured data records Poddar says. And that was possible because an opportunity to select implementations
over JMS, he says. We can then transform of Javas philosophy that you define a specifi- that are best of breed and the most effective blog
that data using JAXB or other Java APIs into cation and let the vendors do the implemen- solutions. </article>
Java beans. Then we compare those beans tation. This puts the customer in full control
to hundreds of other responses and create and gives them the ability to find the right Philip J. Gill is a San Diego, Californiabased free-
a single response formatted in one of sev- itinerary for them. lance writer and editor.
23
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//new to java /

COMMUNITY
Part 1
Learning and Teaching Object
Orientation with BlueJ

JAVA IN ACTION
MICHAEL KLLING A systematic and experimental approach to learning Java
BIO

I n the previous issues of Java We now grow up a bit and shift In future issues of Java Eclipse or (insert your own favorite

JAVA TECH
Magazine, we went step by to BlueJ. BlueJ is a generic devel- Magazine, I will go through a environment here)? The answer
step through a project of build- opment environmentno code small project that can be used to is that the requirements for an
ing a simple game in Java using is magically provided, and we can learn object-oriented program- environment for beginners are
the Greenfoot environment. develop any kind of application we ming with BlueJ and Java. significantly different than the
Greenfoot is a great tool to like. Thus, in its purpose, it is closer requirements for an environment
engage young learners by get- to well-known professional IDEs, Simplicity for professional programmers.
ting them highly motivated very such as NetBeans and Eclipse. The first question many people ask Many software tools that are
quickly. The ease with which However, it is still an IDE focused when I talk about teaching object useful for professionals repre-

ABOUT US
we can put animated graphics on learning object orientation, and orientation and Java to beginners sent only clutter, confusion, and
onscreen is a fantastic help in for a variety of reasons, it is much is, Why not just use NetBeans or unnecessary hurdles for begin-
drawing kids to programming. better suited to beginners than
This time, however, we want to large professional environments.
look at approaching the learning In this article, I will provide an
and teaching of object-oriented overview of BlueJ, which is most
programming more systemati- useful for those of you who can
cally. To support this, we will use already program and are looking
another tool: BlueJ. for a tool to teach programming
The strength of Greenfoot is a to beginners, either at the uni-
quick, playful entry to program- versity level, toward the end of
ming with immediate visual high school (for example, in an AP
results. The drawback, however, computer science course), or in an
is that there is a bit of magic after-school programming club. I
going on: some of the code is will give you an idea what BlueJ is
provided by the environment and what it provides. blog
(the runtime framework), and the The best way to read this article
type of program we can create is is to download BlueJ and install
restricted to two-dimensional it. Then download the people
PHOTOGRAPH BY JOHN BLYTHE graphical applications. project, and play along as we go. Figure 1
24
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//new to java /

COMMUNITY
ners. With big, professional environ- open your first project: the class dia- visualizations and interactions in BlueJ
ments, students spend a large amount gram (see Figure 1). It is the main view entirely remove this problem; students
of their brain power thinking about the of the project and shows the classes in just get it.
environment, rather than thinking about the project and their relationships. The

JAVA IN ACTION
programming concepts. diagram supports and reinforces think- Object Interaction
The first difference in BlueJ is its ing about class structures from the very Once an object has been created on the
simplicity (see Figure 1). Students feel beginning. In early teaching, students object bench, we can interact with this Figure 2
comfortable using the environment very typically do not start with an empty object by invoking its public methods
quickly, and we never teach about the screen. Instead, they are given projects (see Figure 3). Again, if a method has
environment; we teach about concepts. (often partially implemented) to experi- parameters, a dialog box allows us to
You will see what I mean when you start ment with and extend. enter their values. Return values are
BlueJ yourself. After only a few hours, displayed for methods with results.

JAVA TECH
students are entirely comfortable using Interactive Object Instantiation This easy manual interaction allows
the environment. Once a class has been written and a very quick and thorough testing of
compiled, we can right-click the class in code, which can be used to investigate
Figure 3
The Toolset the diagram to see a context menu. This a project to find out what it does or to
The second difference is the toolset menu offers any public constructor to test code that was just written to see
that is provided. Not only does BlueJ allow us to manually create an object of whether it behaves as expected.
provide fewer tools than professional this class (see Figure 2). If the construc- Because testing is possible with-
IDEs, it provides different tools. The tor has parameters, a dialog box pops up out the need to write test drivers, the

ABOUT US
tools provided by BlueJ encourage and to let us enter the necessary values. hurdle to testing is much lower than in
support visualization, interaction, and Once an object has been created, it traditional environments. Therefore,
experimentation. They were designed by appears (in red) on the object bench, students typically test earlier and more
experts in programming education with toward the bottom of the main win- often. Also, because results can be seen
educational theories in mind, and they dow (see Figure 1). When teaching, it is during a test sequence, further tests can
allow a different style of learning than important to create multiple instances be adjusted depending on the previous
standard IDEs offer. of the same classthis makes it very result. This is not the case if tests were
The tools include mechanisms for easy for students to see the difference executed from prewritten scripts. Figure 4
active, direct experimentation with and the relationship between classes Apart from better testing, the
objects. This is one of the and objects: From a class, we interaction reinforces the following By interacting with objects, stu-
most fundamental function- SUPER EASY can create an object. In fact, most-fundamental principles of object- dents are conditioned to think in
alities missing (from an edu- BlueJ provides we can create many objects. oriented programming: terms of objects from Day One. This is
cational viewpoint) in most
environments. Lets have a
probably the most When using traditional
environments, understand-
A program consists of a set of inter-

acting objects.
a fundamental reversal of traditional
approaches that use older textbooks and
look at the most important convenient method ing the difference between We communicate with objects by standard IDEs.
of them. of any environmentclasses and objects is one of
the concepts known to be
invoking their methods.
Methods are provided by the objects. Composition
blog

The Class Diagram for creating JUnitdifficult for students. This is Methods may have parameters and Parameters to methods can be not only
The first visual tool is appar- tests. not surprising if all they ever return values. predefined or primitive types; they can
ent immediately when you look at is lines of code. The Parameters have types. also be objects. Figure 4 shows an exam-
25
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//new to java /

COMMUNITY
ple where a Person object is expected. In BlueJ, we start with the clean prin-
Any object present on the object bench ciples and add the idiosyncrasies of the
can be passed as a parameter (as long as language later. You can, of course, have a
the type matches) by simply clicking it main method and use it if you want to. It

JAVA IN ACTION
when the parameter dialog box pops up. will appear (together with all public static
methods) in the class menu, where it
State can be invoked. However, it is nothing
BlueJ offers an inspector capability special and can be introduced if and
that allows us to open an object and when students are ready to really under-
look inside it (see Figure 5). It is highly stand the meaning of public, static, void,
educational to look into two or three and String[].
objects of the same class and observe

JAVA TECH
their fields. We can see that they all have The Code Pad
the same fields, but their values differ. Another very useful educational tool is
We can even make calls to an objects the Code Pad. The Code Pad is visible at
methods while the inspector is open to the bottom right in Figure 1. It allows us
observe the values changing. This rein- to type individual expressions or state-
forces another important concept: state. ments, which are then immediately
executed. For expressions, the result
Yes, Really: No main Method is immediately displayed in the Code

ABOUT US
Figure 6
If you played along until now, and youre Pad. If the result is an object, it can be
used to writing Java programs, you dragged across to the object bench for
will have noticed one thing: no main further investigation. probably the most convenient method to teach the fundamentals of Java and
method. Yes, thats right: there is no The Code Pad is very useful for stu- of any environment for creating JUnit object orientation to beginners. Until
main method! dents to quickly and easily try out arbi- tests. In addition to the standard writ- then, get BlueJ installed on your system
The main method is an extremely ugly trary code snippets to see what they do. ing of test classes, interactive testing and start experimenting! </article>
hack for connecting a Java program to and regression testing can be combined.
the operating system. It has nothing The Editor We can perform a sequence of interac-
whatsoever to do with object orientation BlueJs text editor highlights scopes, tive tests and record this interaction as a LEARN MORE
and has confused students ever since it such as methods, if statements, and JUnit test case to be replayed later. Java SE 7 API
was first shown. loops with different background color- We will discuss this functionality
ing (see Figure 6). This is another edu- in more detail in a later article in this
cationally valuable visualization. The magazine.
coloring supports the understanding
of scoping, and errors in scope become Conclusion
much more easily apparent. In this article, I presented a quick over- blog
view of the most important tools of the
Unit Testing BlueJ environment. From the next article
Unit testing (using JUnit) is closely inte- onward, we will look at a specific project,
Figure 5 grated in BlueJ. In fact, BlueJ provides and discuss how these tools can be used
26
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//new to java /

COMMUNITY
Part 1
Introduction to Web Service Security
from Server to Client

JAVA IN ACTION
MAX BONBHEL Secure your Web services with Metro, GlassFish, and the NetBeans IDE.
BIO

W eb services are the best In this article, I will demon- Web service to reliable, secured, GlassFish 3.1.2 (available for

JAVA TECH
way to integrate new or strate how to secure Web services and transacted Web services that download here)
extend existing functionality into efficiently both on the server and involve .NET services. The Metro Metro 1.3 or higher (included in

an application, but this causes the client using Metro, GlassFish, platform provides, in one place, NetBeans)
new problems for the security of and the NetBeans IDE. all we need to build production- The AuctionApp project from

data transiting between the client Note: The complete source code quality Web services. Part 3 of Introduction to
and the server. This article is the for the application designed in this RESTful Web Services (avail-
first in a three-part series that article can be downloaded here. What Is WSIT? able for download here)
will focus on the different aspects Web Services Interoperability Note: This article was tested

ABOUT US
of SOAP Web services, such as What Is Metro? Technology (WSIT) is a part of with the latest version of the
security, reliability, and transac- Metro (included in the NetBeans the Metro Web service stack NetBeans IDE (version 7.1.2, as of
tions. The goal of this series is to IDE) is a high-performance, along with the Java API for this writing).
highlight methods for increasing extensible, easy-to-use Web ser- XML Web Services Reference
the security of applications within vice stack. It is a one-stop shop Implementation (JAX-WS RI). It Overview of Adding Security
the context of increasingly com- for all your Web service needs, provides a complete architec- Options to the Web Service
plex systems. from the simplest hello world ture and tools for developing the What we are going to do is secure
next generation of Web service the service and the client of the
technologies. WSIT consists of AuctionApp project we created
Java APIs that enable advanced in the previous series of articles
Web service features to facilitate (Introduction to RESTful Web
interoperability with .NET. Services) by performing the fol-
lowing tasks:
Prerequisites Secure the Web service:

Download the following soft- Add a security mecha-

ware, which was used to develop nism called Username blog


the application described in this Authentication with
article: Symmetric Key.
Author Max Bonbhel demonstrates how to NetBeans IDE 7.1.2 (available Import the certificates into
PHOTOGRAPH BY
ALLEN MCINNIS/GETTY IMAGES
secure your Web services. for download here) the GlassFish application
27
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//new to java /

COMMUNITY
server and set up a default user for
this application.
Configure the client that references

the secured Web service.

JAVA IN ACTION
Test the secure Web service:

Use the Username Authentication

with Symmetric Key security


mechanism.
Provide the certificates and use a

default user credential to access Figure 2


the secured service.
The application we are going to secure

JAVA TECH
is an online auction place (like eBay)
that we created in the previous series
of articles. Sellers post their items in
listings, and buyers bid on the items. A
seller can post one or many items, and a
buyer can bid on one or many items.
Specifically, we are going to limit Figure 1 Figure 3
access to the JAX-WS Web service that

ABOUT US
extrapolates the amount of a bid.
d. Make sure the Reliable Message configuration for the Web service based default credentials to access the secured
Secure the Web Service Delivery option is deselected. on the options we selected. Web service.
Lets secure the Web service in two min- e. Select Secure Service and select 3. Deploy the Web service by right- 1. Refresh the Web service client:
utes using the NetBeans IDE. Username Authentication with clicking the AuctionApp project node a. Make sure the AuctionApp is up
1. Add a security mechanism called Symmetric Key from the Security and choosing Deploy. and running. If it is not, right-click
Username Authentication with Mechanism list. NetBeans creates a new WSIT config- the AuctionApp node and select
Symmetric Key in the AuctionApp 2. Import certificates into the GlassFish uration file that contains detailed infor- Deploy.
application: application server and set up a mation about the options and the run- b. Open the AuctionAppWeb-
a. Open the AuctionApp project in default user, so we can use the server time usage of the secured service. The ServiceClient project in NetBeans
NetBeans IDE 7.1.2 or higher. immediately to test our application: file is generated in the Web Pages/WEB- IDE 7.1.2 or later. Expand the Web
b. Expand the Web Service node of a. Select Use Development Defaults INF node of the AuctionApp project. Service References node of the
the AuctionApp project and right- to import certificates and set up a AuctionAppWebServiceClient
click the AuctionAppSOAPws default user, as shown in Figure 1. Configure the Client project and right-click the
node; then select Edit Web Service This option allows NetBeans to import In this section, we are going to refresh AuctionAppSOAPws node; then
Attributes. certificates into the application server and configure the Web service client select Refresh. blog
c. Under the Quality Of by creating an entry in the GlassFish that references the Web service that was c. From the Confirm Client Refresh
Service tab, expand the keystore and truststore. secured in the previous section. wizard, select Also replace local
AuctionAppSOAPwsPortBinding b. Click OK. The Web service client will use the wsdl file with original wsdl located
section (see Figure 1). NetBeans generates the appropriate certificates that were imported and the at:, as shown in Figure 2.
28
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//new to java /

COMMUNITY
d. Click OK. References node of the
At this point, the Web service client is AuctionAppWeb-
regenerated from the corresponding ServiceClient project
Web Services Description Language and right-click the

JAVA IN ACTION
(WSDL) file. AuctionAppSOAPws
2. Open the AuctionAppSOAPws node; then select Edit
.xml file located in the Source Web Service Attributes.
Packages/META-INF node of the c. Under the Quality Of
AuctionAppWebServiceClient project. Service tab, expand the
The wsp: Policy tags in the Security section.
AuctionAppSOAPws.xml file should d. Make sure the Use devel-
look as shown in Figure 3. opment defaults option

JAVA TECH
3. Deploy the client application is deselected, as shown in Figure 4 Figure 7
by right-clicking the Figure 4.
AuctionAppWebServiceClient project e. Click OK.
node and choosing Deploy. f. Right-click the
AuctionAppWeb-
Test the Secured Web Service ServiceClient project and
Now its time to test the service. We will choose Clean and Build.
invoke the secured Web service from the g. Right-click the

ABOUT US
client application. AuctionAppWeb-
We are going to use a sample front- ServiceClient project
end JavaServer Faces (JSF) application to again and choose Run.
perform the following tasks: The list of all entries is dis-
Try to invoke the secured Web service played, as shown in
without providing the certificates and Figure 5.
Figure 5 Figure 8
the default user. h. Click the Show all Bid
Use the certificates and the default Items link to display
user to invoke the secured Web ser- the list of bid entries, as
vice that extrapolates the amount of shown in Figure 6.
a bid. i. Click the View link for the
1. Try to invoke the secured Web service bidder named Vals to see
to display the extrapolated amount of the newly extrapolated
a bid: amount of the Vals bid, as
a. Make sure the AuctionApp project shown in Figure 7.
we opened previously is up and As you can see, the amount blog
running. If it is not, right-click of the bid changed from
the AuctionApp node and choose 12.0 to 0.0. This means that
Deploy. the client failed to call the
b. Expand the Web Service secured Web service. Figure 6 Figure 9
29
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//new to java /

COMMUNITY
2. Use the certificates to invoke the newly extrapolated
the secured Web service amount of the Vals bid, as
to display the extrapolated shown in Figure 9.
amount of the bid: As you can see, the amount

JAVA IN ACTION
a. Make sure the AuctionApp of the bid changed from 12.0 to
we opened previously is 1200.0. This means that the cli-
up and running. If it is not, ent was able to call the secured SEPT. 30 - OCT. 4 | SAN FRANCISCO
right-click the AuctionApp Web service. Bravo!
node and choose Deploy.
b. Expand the Web Service
References node of the
AuctionAppWebService
Conclusion
In this article, we have seen how
easy it is to configure security
REGISTER NOW
Save $200 by Sept. 28th

JAVA TECH
Client project and right- and reliability into an existing
click the AuctionApp Web service and set up default
SOAPws node; then credentials to access the service.
select Edit Web Service The bundled GlassFish keystore
Attributes. and truststore files were very Register at oracle.com/javaone
c. Under the Quality Of useful. We used NetBeans and
Service tab, expand the Metro to automatically update
Security section. these files and use them imme-

ABOUT US
d. Select the Use develop diately for development.
ment defaults option, as In Part 2 of this series, we
shown in Figure 8. will focus on importing specific
e. Click OK. certificates into the GlassFish
f. Right-click the AuctionApp keystore and truststore so that Silver Sponsor

WebServiceClient project they can be used in a production


and choose Clean and environment. </article>
Build. Bronze Sponsors

g. Right-click the
AuctionAppWebService LEARN MORE
Client project again and NetBeans Advanced Web Service
choose Run. Interoperability manual
The list of all entries is dis-
Metro User Guide
played, as shown in Figure 5.
GlassFish resources
h. Click the Show all Bid
Items link to display the list blog
of bid entries, as shown in
Figure 6.
i. Click the View link for the
bidder named Vals to see
30 Copyright 2012, 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.
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
GlassFish Monitoring with LightFish

A Conversation with

JAVA IN ACTION
Adam Bien
Java Champion Adam Bien discusses his new open source
Java EE 6 stress test monitoring tool. BY ARUN GUPTA

JAVA TECH
A
dam Bien is no stranger Java Magazine: You recently released
to Java developers, espe- LightFisha GlassFish monitoring tool. Tell us
cially those of the Java EE about it.
stripe. He is a celebrated Java Bien: Stress tests are widely underestimated.
Champion and a JavaOne Rock In my client projects, I started to write simple
Star who has given highly rated tools to gather and analyze performance statis-

ABOUT US
sessions at JavaOne, and he was tics during stress tests. For the Java Magazine
named 2010 Java Developer of article Stress Testing Java EE 6 Applications, I
the Year by Oracle Magazine. wrote such a tool from scratch. During the 2011
He works as a consultant in his JavaOne conference in San Francisco, an Oracle
native Germany (and through- engineer asked me to participate in his talk and
out the continent) and is the demonstrate the tool in action. After the session
author of several books on Java. I got the idea of open sourcing the tool, which
We caught up with him to learn was named STM at the time. In fact, the first
about LightFish, an open source commit happened during the JavaOne confer-
monitoring tool for GlassFish. ence and is still visible in the git logs.
LightFish is a Java EE 6 application that can
be deployed on any Java EE 6 application server
you like. LightFish accesses the GlassFish under
Stress machine (see Figure 1) remotely via REST,
gathers and persists the monitoring data, and
re-exposes the data via REST again. LightView, blog
the real-time monitoring client, always accesses
the LightFish instance and never the GlassFish
under Stress machine.
PHOTOGRAPHY BY
PIOTR MALECKI/GETTY IMAGES
31
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
Java Magazine: Talk about local deployment controller] pattern with data binding. Each
for development time monitoring and remote chart is bound to an attribute of the Snapshot
monitoring for production usage. What kind entity. Because the monitoring data is per-
of telemetry data can be monitored? sisted, you can use any reporting tool you like

JAVA IN ACTION
Bien: Everything that GlassFish exposes. The to analyze the data after the tests.
GlassFish REST monitoring API exposes the Java Magazine: Does LightFish provide an
data in a consistent way. Picking the right extensible architecture that allows users to
attribute is a matter of performing a single expose their own monitoring data?
method invocation. Currently, LightFish Bien: The recent version of LightFish sup-
monitors only the essential data: ports scripting. You can register persistently
monitoringTime, usedHeapSize, threadCount, at runtime new rules written in JavaScript,
peakThreadCount, totalErrors, currentThread- which are evaluated against the recent and

JAVA TECH
Busy, committedTX, rolledBackTX, the current Snapshot instances. You can eas-
queuedConnections, activeSessions, ily express something like please notify me
expiredSessions, and escalationReason, as well if the heap size increase reaches a certain
as the monitoring data of all size. In this case, LightFish will
installed JDBC connections, the create a new Escalation chan-
SIMPLE RULES
list of all installed applications, nel for you at runtime. You can
and the uptime (see Figure 2). Premature subscribe to it with any tool you
These attributes should be optimization is the like. And the JavaFX 2.0 client,

ABOUT US
Figure 1
self-descriptive. They are the
attributes of the JPA [Java
root of all evil is LightView, creates a new tab
and displays all the escalated
Persistence API] Snapshot entity, particularly true for values in a table.
columns in the database, as Java EE 6. Write The structure is hardcoded in
well as the attributes exposed
as an XML entity with the same
simple business the Snapshot entity. To analyze
metrics that have not yet been
structure. The whole metadata code, stress test exposed, you have to extend
is derived from a single entity. often, and optimize the Snapshot and LightView.
The JavaFX 2.0 client calls
LightFish via a GET HTTP request.
on demand. The addition of a monitoring
attribute usually takes about 15
LightFish blocks the connection minutes with testing.
and waits until the availability of However, Im thinking about
the next Snapshot initiated by the implementing a plug-in system.
EJB timer expiration. The user gets the illusion Java Magazine: Suppose Im building Java
of real-time monitoring without overload- EE 6 applications on GlassFish. How can I
ing the server. LightFish uses asynchronous benefit from LightFish? blog
Servlets 3.0 to implement this functionality Bien: As a Java EE 6 developer, you have the
and can actually handle several thousand unique opportunity to fully focus on the
monitoring clients. The JavaFX 2.0 application realization of business logic without think-
Figure 2 was built according to the MVC [model-view- ing too much about framework libraries and
32
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
the infrastructure. LightFish helps to identify Java Magazine: What are your future plans,
potential bottlenecks during nightly stress and how can the Java EE 6 community help
tests. Premature optimization is the root of improve LightFish?
all evil is particularly true for Java EE 6. Write Bien: Theres a lot to do. Right now LightFish

JAVA IN ACTION
simple business code, stress test often, and monitors only Java EEspecific behav-
optimize on demand. ior. I would like to dig into EJB [Enterprise
Java Magazine: What GlassFish features were JavaBeans] and JPA metadata as well. Im
used to build this application? also thinking of analyzing any application-
Bien: LightFish relies exclusively on dependent monitoring information. If you
GlassFishs management and monitoring have an idea, just fork LightFish at github
REST APIs. LightFish uses the REST manage- Adam Bien demonstrates LightFish. .com/AdamBien/lightfish. I have only one
Java Champion ment API to enable monitoring and the REST requirement: the code should be developed
Adam Bien and Java

JAVA TECH
monitoring API to fetch the monitoring data. in the Java EE wayas simply as possible
Evangelist Arun Gupta There is no binary dependency on GlassFish. with minimal (none would be best) external
discuss LightFish You could easily port LightFish to other appli- to be able to monitor, for example, JBoss. dependencies. LightFish is developed under
while getting a
cation servers. The REST interface is vendor- Hence, Im using GlassFish in the majority of the Apache license.
caffeine fix. Both were
in Pozna, Poland, specific, so you will have to reimplement a my projects. I do not plan to reimplement the Java Magazine: How can developers get
for the GeeCON 2012 single methodorg.lightfish.business.monitor- method yet. started?
conference in May. ing.control.SnapshotProvider#fetchSnapshot Java Magazine: Is there any performance Bien: Download lightfish.war and drop it
overhead? into the glassfish/domains/domain1/

ABOUT US
Bien: LightFish polls GlassFish. In the default autodeploy folder. LightFish should install
case, LightFish will execute several GET in a few seconds. No further interaction is
requests every two seconds. This is just a needed. Then I would download the code. I
default, and it is configurable at runtime. tried to write simple code without any bloat.
During nightly stress tests, you can use a I even used LightFish code at recent confer-
longer interval and minimize the impact. ences to explain Java EE capabilities. Ive also
LightFish continuously monitors my x-ray recorded an introductory screencast [click the
blog statistics software with negligible play button, left, to watch]. </article>
overhead.
Java Magazine: Why did you choose GlassFish Arun Gupta (@arungupta) is a Java evangelist
to be the first app server? And, do you plan to at Oracle, where he works to create and foster the
port this application to other app servers? community around Java EE, GlassFish, and Oracle
Bien: My clients have been using GlassFish WebLogic Server. He has more than 15 years of
since version 2.0. I use GlassFish because all experience in the software industry.
my Java EE projects are based on GlassFish.
Porting LightFish to another application LEARN MORE blog
server is easy, but it is a rather boring task. I
Adam Biens blog
would prefer to implement new functional-
ity instead. LightFish is my leisure-time open
source project and, thus, it should be fun.
33
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
C HO O S E YO UR TO O L

COMMUNITY
01 02 03 04 05 06

DEVELOPER

JAVA IN ACTION
01 BUILD AUTOMATION TOOLS

POWER
02 CONTINUOUS INTEGRATION TOOLS

03 OPEN SOURCE MODULES

04 SOFTWARE CONFIG MANAGEMENT

JAVA TECH
05 REPOSITORY MANAGEMENT

06 RUNTIME ANALYSIS

With a bevy of Web-based development tools

ABOUT US
available, its a great time to be a Java developer.
BY STEVE MELOAN
WITH CONTRIBUTIONS BY JANICE J. HEISS

M
odern era agile software develop- source modules and frameworks obtained in discusses many of the tools available today;
ment is predicated upon iterative, a sometimes unregulated and undocumented however, this is by no means a complete,
incremental development processes, fashion across the internet. definitive list. You may have other favorites
with continuous integration (CI) of fixes and Fortunately, a rich stack of tool offerings that are not included; let us know. blog
enhancements. With the need for such CI enables development teams to more effec- Java.net, among other things, provides a
comes the complexity of managing geographi- tively track, build, integrate, and manage soft- delivery channel for some of the technologies
cally distributed teams that are utilizing open ware projects and their modules. This article described in the following pages.

PHOTOGRAPHY BY BOB ADLER


34
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
C HO O S E YO UR TO O L

COMMUNITY
E X PER T OPINION 01 02 03 04 05 06
For me, the real difference
I find Apache Ant

01
is between tools that have
(Another Neat Tool) very
useful for automating the
a point of view about how
development processes BUILD AUTOMATION TOOLS
build process. I especially should work and those that dont. I call
appreciate its use of XML, which facilitates these two types tools and metatools.

JAVA IN ACTION
build-script creation, and the JUnit task, A build automation tool ideally provides

Ant/Ivy 101
Maven is a build tool, because it essentially Apache Ant.
which facilitates integration of JUnit test- forces you to adapt to the Maven lifecycle the ability to build a given project with a
single command, mobilizing all the Similar to the
ing into the process. and way of doing things. Ant doesnt come decades-old
Jeff Friesen, with such a point of viewinstead, you modules, artifacts, libraries, and code
UNIX Make in some respects, Apache Ant
Freelance Developer and Educator have to build up targets and a sequence necessary to that project.
is written in Java and is best suited to
based on your own project lifecycle. Some Apache Maven. Hosted by the Apache
building Java projects. It uses an XML file
teams prefer the additional structure which Software Foundation and written in Java, (build.xml) to define a given build process
I love using Maven in large comes with a tool like Maven, whereas other Maven can be used to build projects in and its dependencies. Within the build file,
organizationswhere many teams object to having to fit in with the

JAVA TECH
Java, as well as C#, Ruby, Scala, and other Ant can also delegate build work to either
developers are working on demands of the Maven lifecycle. languages. It operates from an XML file, native or Java-based external programs.
multiple projects. Some very Ben Evans, Coauthor, but uses a very different paradigm from One of Ants primary goals was to solve
deep thought about the software project The Well-Grounded Java Developer Ant. Rather than simply chaining together the portability issues of Make, where dif-
lifecycle has gone into Maven over the years, sequential build tasks, as occurs with ferent platforms required different script
and its strict standards approach works bril- commands. Ant provides built-in func-
Ant, Maven defines a project in terms of
liantly where chaos can potentially abound. Identifying and download- tionality designed to behave the same on
its dependencies, external modules and
It doesnt matter which project developers ing the correct versions of a all platforms. It has limited fault-handling
components, build order, directories, and
join. A Maven mvn clean install command

ABOUT US
Java projects dependent JAR required plug-ins. Maven projects are capabilities and no persistence of state, so
builds, tests, packages, and installs a local files, which may have been it is primarily useful only for classic build
copy of the application for them, letting defined via a Project Object Model (POM)
obtained from a variety of online sources, is and test processes.
them get started with their coding. file (pom.xml). Maven dynamically down-
a thankless and often error-prone activity. Ant is supported by most major IDEs,
Having good build and CI processes in Maven takes care of this for you, and effec- loads Java libraries and Maven plug-ins
including Eclipse, IntelliJ, JBuilder,
place means that you can write code more tively structures your project so as to elimi- from either the Maven Central repository
JDeveloper, NetBeans, and WebSphere.
quickly and maintain a higher bar of qual- nate a host of setup and configuration issues. or other defined software repositories. Apache Ivy. Written in Java, Apache Ivy
ity. In conjunction with TDD [test-driven Maven provides plug-ins that encourage and Larger Maven projects are typically is a subproject of the Apache Ant project,
development], build and CI means you can promote good standard software practices divided into several subprojects, each serving as a transitive relation depen-
rapidly refactor without fear! Think of it as including unit testing, version control, and with its own POM file, but with a root dency manager. An XML file defines
having a mentor looking over your shoulder standardized release processes. POM to compile the master project via project dependencies and the resources
providing a safe and controlled environment A controlled process like Mavens makes a single command. The Maven plug-in necessary to build the given project.
in which you can quickly code and make development within a team far more effi- architecture allows it to interface with Ivy resolves and downloads required
bold changes. cient and scalable. And the documentation resources from the specified repositories.
build tools for other languages, including
Martijn Verburg, Coauthor, and site reports add to Mavens value as Whereas Maven is a complete build tool,
the .NET framework and C/C++. Popular
The Well-Grounded Java Developer a full-featured project management and with built-in dependency management,
IDEs that support development with
comprehension tool. Maven include Eclipse, IntelliJ, JBuilder, Ivy focuses specifically on dependency blog
Cas Saternos, Oracle Certified DBA and management functionality, working in
JDeveloper, and NetBeans.
Sun Certified Java Programmer partnership with Ant.
Gradle. Written in Java and Groovy, Gradle
builds upon the concepts of Ant and
Maven but uses a Groovy-based Domain-
35
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
C HO O S E YO UR TO O L

COMMUNITY
01 02 03 04 05 06
E X PER T OPINION
Hudson/Jenkins are CI Combining smart features Specific Language (DSL) rather than XML. ligently determines which part of a build
tools, so the first thing that of both Ant and Maven, Gradle uses a directed acyclic graph (DAG) tree is current, so that already up-to-date
comes to mind is that they and being powered by to determine the order in which build dependent branches neednt be rebuilt.
execute tests. Correct. But Groovy, Gradle provides

JAVA IN ACTION
tasks should be run. Gradles DSL is exten- Gradle offers support and transitive
they do so much more. With the proper set a new and powerful way to handle your sible, allowing for the addition of new dependency management for existing
of plug-inssuch as test coverage and delivery pipelines. language elements or the enhancement Maven and Ivy repositories and also pro-
static analysisthey provide everyone in the Michael Httermann, Java Champion of existing elements. Intended to manage vides a converter to translate Maven POM
development team with a highly valuable
large, multiproject builds, Gradle intel- files into Gradle scripts.
information center on the health of the proj-
ect. Developers can autonomously verify the

02 CONTINUOUS INTEGRATION TOOLS


Having been a Java devel-
quality of the code they are writing, and proj- oper since nearly the begin-
ect leaders can keep everything under con- ning (summer of 95), I have

JAVA TECH
trol, monitoring both the progress and the a collection of open source
technical debt. The best of Hudson/Jenkins projects that I either founded or still main-
happens with Maven-based projects, thanks tain. As a full-time researcher, and also a When properly implemented, CI requires and monitoring the results of externally
to Maven profiles. This combination makes new father, I need a system to reliably man- that each commit of new software be run jobs (such as cron jobs), including
it easier to build on multiple configurations age these projects and push out releases. accompanied by a complete build and those that execute on remote machines.
such as JDKs and databases. In addition, Thats what Hudson is to me. Ive been run, and that it pass all defined unit tests. Results can be monitored via e-mail or
Maven can warn you about whether the using it for several years now and continue With the advent of CI tools, this change RSS, and third-party plug-ins offer addi-
library versions youre using will break your to love itit just works. in commit functionality has increasingly tional extensible functionality.

ABOUT US
build due to a regression. Josh Marinacci, Java Champion become highly sophisticated and auto- Hudson is written in Java, and runs in a
Fabrizio Giudici, mated. CI tools include CruiseControl, Servlet container (such as Apache Tomcat
Senior Java Architect, Tidalwave Hudson, Jenkins, Bamboo, BuildMaster, or GlassFish). It can execute Ant- and
Jenkins is an awesome tool AnthillPro, and Teamcity. Maven-based projects as well as simple
for continuous integration. The big-picture goal of such CI tools is shell scripts and Microsoft Windows batch
My metatool of choice is With it, you can combine all to wrap configurable intelligence (that commands, and can distribute build/
NetBeans, Java EE Edition. the work of a team with less can be extended with plug-ins) around test loads to multiple computers, as well
It integrates Maven 3; error and more quality/productivitywhile the process of version control, builds, as keep track of which builds produced
JUnit; Ant; Hudson/ monitoring status and the number of tests. testing, and reporting of results. Below is which JARs. Plug-ins provide integration
Jenkins; and countless Java EE hints, wiz- And, yes, you can use JUnit! There are a sampling of popular CI tools, including with most version control systems and
ards, and extensions. You get an extremely almost too many available plug-insfor
two recent winners of the Dukes Choice bug databases and can add new func-
productive environment with a single click example, Sonar, which verifies the quality of
no plug-in fiddling required. Award, Hudson and Jenkins. tionality or even change the appearance
your teams code, test coverage, duplication
Adam Bien, Java Champion Hudson. Winner of the 2008 Dukes of Hudson. Meanwhile, build test reports
of code, and so on.
Otvio Gonalves de Santana, Choice Award in the Developer Solutions can be generated in a variety of formats
JUG Leader, Java Bahia category, Hudson is a popular alterna- (JUnit is supported out of the box).
tive to CruiseControl. Hudson provides Oracle continues to develop Hudson blog
an easy-to-use, GUI-based configurable along with the community at large. But
system for integrating changes to a in January 2011, a fork of the project was
projectobtaining explicit fresh builds created and named Jenkins.
of the project, scheduling future builds, Jenkins. Originally begun as the Hudson
36
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
C HO O S E YO UR TO O L

COMMUNITY
01 02 03 04 05 06

03
CI tool, the Jenkins project was created in as Ant and Maven, as well as a standard
January 2011. Both Hudson and Jenkins
consider the other to be a fork, with sepa-
exec builder; and ports of CruiseControl
for .NET (CruiseControl.NET) and Ruby
OPEN SOURCE MODULES
rate development branches. (CruiseControl.rb).

JAVA IN ACTION
Winner of the 2008 Dukes Choice ToolsCloud. Almost in a conceptual cat- Because modern software development tively locate and process the information.
Award (as Hudson) in the Developer egory by itself, ToolsCloud is effectively involves geographically distributed teams In the case of a typical Maven reposi-
Solutions category, Jenkins provides an a hybrid cloud-based IDE that includes that use diverse open source modules tory, the binary artifact is a JAR file, but it
easy-to-use, GUI-based configurable project management, CI functionality and frameworks acquired from across could just as easily be a Flash library or
system for integrating changes to a (including build automation and auto- the internet, projects can run consider- a Ruby library. When a Maven POM file
project, obtaining explicit fresh builds mated testing), metrics and analysis, able security, consistency, and reliability lists a project dependency that includes
of a project, scheduling future builds, and a broad array of development tools. risks. According to a survey conducted by a repository-based entry, it downloads
and monitoring the results of externally Available via a monthly subscription plan, Sonatype, more than 80 percent of typi- that entrys POM, and then downloads

JAVA TECH
run jobs (such as cron jobs), including and hosted on Amazon Elastic Compute cal software applications consist of open any libraries or modules required by that
those that execute on remote machines. Cloud (EC2), ToolsCloud includes Git source components and frameworks. Yet dependency. This ability to determine
Results can be monitored via e-mail or (software configuration management), many studies find a staggering use of vul- a projects dependencies and transitive
RSS, and third-party plug-ins offer addi- Redmine (project management and bug- nerable, insecure, and nondocumented dependencies is made possible by the
tional extensible functionality. tracking tool), Nexus (artifact manage- open source offerings. Sonatype finds standards and structure of the repository.
Jenkins is written in Java, and runs ment), Hudson/Jenkins (CI), and more. that only 32 percent of teams maintain a Sonatype/Central repository. The default
in a Servlet container (such as Tomcat ToolsCloud features a management detailed bill of materials record of the configuration of Maven retrieves soft-
or GlassFish). It can execute Ant- and calendar and tracking, reporting, and sta- open source components in their devel- ware artifacts from the Central reposi-

ABOUT US
Maven-based projects as well as simple tistics tools as well as metrics history and opment stack. The survey also revealed tory, a public facility that is stewarded
shell scripts and Windows batch com- analysis tools. It easily integrates with that only 50 percent of developers report by Sonatype. Central reportedly receives
mands, and can distribute build/test your IDE of choice. that their company has an open source four billion requests per year, contains
loads to multiple computers, as well software policy. 300,000 components, and is accessed
as keep track of which builds produced Code/artifact repository. In order to deal by 60,000 development organizations
which JARs. Plug-ins provide integration E X PER T OPINION with an ever growing and ever more com- worldwide. The average enterprise report-
with most version control systems and plex open source ecosystem, enterprises edly downloads more than 1,000 unique
bug databases and can add new func- Using Jenkins is like are increasingly turning to code reposito- components from Central each month.
tionality or even change the appearance having an extra member ries and cached repository management Repositories such as Central and tools
of Jenkins. Meanwhile, build test reports
in your development team. systemsestablishing a centralized, such as Maven typically use a Group,
It relentlessly builds and
can be generated in a variety of formats secure, and managed code repository for Artifact, Version (GAV) coordinate sys-
tests your software, preventing mistakes
(JUnit is supported out of the box). the artifacts required to build and main- tem as a means of storing and locating
and freeing up time so that your team can
CruiseControl. Written in Java, focus on simply producing great software. tain projects. a given artifact: http://repo1.maven.org/
CruiseControl provides an extensible Juliano Viana, A code repository establishes a platform groupID/artifactID/version/.
framework for custom CI processing. Its Founder and CTO of LogicStyle for the storage, retrieval, and manage- For example, components produced by
features include a Web interface to moni- ment of the binary software artifacts and the Maven project at the Apache Software blog
tor current and past builds; plug-ins for a metadata necessary for a given project or Foundation would be stored/located
variety of source controls, build technolo- application. The information is archived under a groupID of org.apache.maven.
gies, and notification schemes; interfaces and organized in such a way that build An artifactID is the identifier for a given
for popular build automation tools such tools such as Maven or Ant/Ivy can effec- component. The combination of groupID
37
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
C HO O S E YO UR TO O L

COMMUNITY
01 02 03 04 05 06

05 REPOSITORY MANAGEMENT
and artifactID uniquely identifies a given While Maven can be configured to
project, and the version identifier speci- retrieve software artifacts directly from
fies the version of the project, while the one of the many Central mirror sites
packaging identifier specifies the binary around the world (or any external reposi-

JAVA IN ACTION
software format. tory), an increasingly popular option that A repository management system offers Nexus offers cached components for
Once an artifact is assigned a release is faster, more secure, and more eas- a locally cached proxy between develop- quick download, ensures that all users
number on Central, the file contents ily managed is to employ a repository ment teams and external repositories. It access the same modules, enablessecure
cannot be altered. The Central repository manager as a locally controlled proxy to speeds download times, ensures man- and controllable deployment of internally
also contains cryptographic hashes and Central and other artifact repositories aged and configurable access to both developed components, and provides
PGP signatures that can be used to verify (such as those provided by Oracle, Red external artifacts and internally cre- configurable, partner-specific access.
artifact authenticity and integrity. Hat, and Codehaus). ated modules, and provides tagged and Meanwhile, user-defined metadata offers
searchable metadata. rich and customizable search capabilities.

04 SOFTWARE CONFIG MANAGEMENT

JAVA TECH
Sonatype Nexus. Nexus is a managed, JFrog Artifactory. Winner of the 2011
central point of access for external repos- Dukes Choice Award for Innovative Tool
itories, offering configurable permissions for Developers, JFrog Artifactory is a Java-
and customizable/searchable user- based binary file repository management
Software configuration management trol and SCM system, suitable to handle defined metadata. Figure 1 depicts how tool, with a free open source version, a
(SCM) entails rigorously controlling both large and small development proj- a repository manager fits into a typical paid Pro version, and a software-as-
and tracking changes made to soft- ects. GitHub provides a collaborative, development process. a-service (SaaS) cloud-based version
ware, and includes a subfunctionality Web-based facility to manage both public Nexus provides a centralized point for (Artifactory Online). Figure 2 shows how

ABOUT US
of revision control (version handling). and private Git repositories. Written managed access of open source software Artifactory acts as a proxy between your
Development tools such as Hudson and using Ruby on Rails, GitHub is the most components and their dependencies, Maven client and the outside world.
Jenkins (explored earlier) offer support popular Git hosting site, providing social serving as a configurable proxy between JFrog Artifactory serves as a proxy
for a variety of such SCM tools, including networking functionality and usage data organizational and public repositories. between build tools such as Maven, Ant,
Clearcase, CVS, Git, and Subversion. specifically directed toward collaborative
Git. Git offers a distributed revision con- development. Developer Teams
Central Repository

E X PER T OPINION Artifactory is a great


Nexus is a rock-solid vault choice for DevOps. Its
for your binaries, tailor- integration with Jenkins
made for a Maven-based offers full traceability
build process. across builds, links back to tickets, and Nexus OS
allows comfortable build promotions. Easy Build/CI
John Ferguson Smart, Systems
CEO, Wakaleo Consulting configuration, openness, and extensibility
make Jenkins a central service hub and a
smart backbone of your continuous deliv- blog
ery and DevOps infrastructure.
Michael Httermann, Java Champion

Figure 1
38
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
C HO O S E YO UR TO O L

COMMUNITY
01 02 03 04 05 06

06
Ivy, Gradle, and so onproviding local,
E X PER T OPINION
fast-access caching of remote artifacts,
offering configurable management of
RUNTIME ANALYSIS
VisualVM is a tool that
repository access permissions and every Java developer
should become familiar

JAVA IN ACTION
customizable/searchable user-defined While not explicitly directed at collabora- Innovation Award for Most Innovative
metadata. Artifactory is built on top of tive software development/management, Java Technology. At JavaOne 2011, JRebel with. It comes as part
the Java Content Repository (JCR), pack- runtime analysis tools offer an essential was awarded the Dukes Choice Award of every modern Java SDK and enables
aged as a standard Java EE Web applica- debugging/tuning window into applica- for Innovative Compiler for Java Code. developers to visualize the internals of
tion, and deployable into any standard tions during actual execution and are, Java-based and usable on any operat- their applications as they run, helping
Servlet container (Tomcat, WebSphere, therefore, an often-used tool class in the ing system that supports Java, JRebel is diagnose even the most-difficult per-
formance problems. And the integration
JBoss, GlassFish, and so on.) development lifecycle. IDE agnostic and designed for integra-
with BTrace means that you can perform
The Jenkins CI Artifactory Online VisualVM. VisualVM provides an intuitive, tion with various Java EE standards and
complex inspections on running produc-

JAVA TECH
repository servicea Jenkins/JFrog graphical interface that allows developers Java application servers. It is freely avail- tion systems, without affecting end-user
collaboration offering a cloud-based to monitor and troubleshoot executing able to open source software projects experience.
Artifactory repository solution developed Java applications. While VisualVM itself and developers using Scala. It supports Juliano Viana,
specifically for the Jenkins community requires JDK 6 to run, it can monitor any immediately visible code changes with- Founder and CTO of LogicStyle
was announced at the April 2012 Jenkins application running at JDK 1.4.2 or greater. out redeploying; handles changes to class
User Conference in Paris, France. Utilizing such technologies as jvmstat, structures, frameworks, and Java EE; and
Java Management Extensions (JMX), the supports all major Java application serv-
Serviceability Agent (SA), and the Attach ers, IDEs, and frameworks. It eliminates
I think VisualVM is

ABOUT US
underrated by many Java
Maven Clients API, VisualVM displays both local and memory leaks and build time during
developers. Not only does
remote applications, offering visual data development and supports Apache Ant
it enable you to monitor
on CPU usage, Garbage Collection (GC) and Apache Maven. </article> memory consumption and threads, its
activity, heap and permanent generation invaluable when it comes to memory
memory, loaded classes, running threads, analysis. With this tool, Ive easily found
and more. VisualVM also allows for offline Steve Meloan is a former C/UNIX software the causes of a number of memory leaks
analysis of core dumps, as well as analy- developer who has covered the Web and in customer projects.
the internet for such publications as Wired,
sis of taken thread dumps, heap dumps, Fabrizio Giudici,
Rolling Stone, Playboy, SF Weekly, and the
and profiler snapshots. And because San Francisco Examiner. He recently published Senior Java Architect, Tidalwave
Artifactory VisualVM is built on the NetBeans plat- a science-adventure novel, The Shroud, and
form, it is readily extensible with plug-ins regularly contributes to The Huffington Post.
Remote (available at the VisualVM Plugin Center).
Repositories Finally, VisualVM can be integrated with Janice J. Heiss is the Java acquisitions editor at
such IDEs as Eclipse and NetBeans. Oracle and a technology editor at Java Magazine.
JRebel. Developed by Jevgeni Kabanov
and Toomas Rmer of ZeroTurnaround, blog
JRebel is a plug-in for the Java Virtual
Machine (JVM) that enables instant
reloading of changes made to a Java
Figure 2 class file. In 2011, JRebel won the JAX
39
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
HotSpots Hidden Treasure

JAVA IN ACTION
The HotSpot Serviceability Agents powerful tools can debug live Java processes and core files.

POONAM BAJAJ T he HotSpot Serviceability


Agent is a hidden treasure
present in the JDK that very
tion SA binaries that are present in
the JDK. There are two SA binaries
that are shipped with the JDK:
Why Use SA?
Why use SA when we have native
debugging tools such as dbx,
thread objects, and internal rep-
resentations of the Java HotSpot
VM. SA makes it very easy for us
BIO few people know about. The For Microsoft Windows: GDB, WinDbg, and many others? to examine the Java-level details

JAVA TECH
Serviceability Agent (SA) is a set sa-jdi.jar and jvm.dll First, SA is a Java-based, and JVM-level details of the Java
of Java APIs and tools that can be For Oracle Solaris and Linux: platform-independent tool, so it process or core file.
used to debug live Java processes sa-jdi.jar and libsaproc.so can be used to debug Java pro-
and core files (also called crash These binaries provide the SA cesses and cores on all the plat- SA Debugging Tools
dumps on Microsoft Windows). Java APIs and also include useful forms where Java is supported. There are two main SA debugging
SA can examine Java processes debugging tools implemented Additionally, debugging a Java tools implemented using SA APIs:
or core files, which makes it suit- using these APIs. process or the Java HotSpot VM HSDB, which is a GUI tool and

able for debugging Java programs with native debuggers is very the main debugger

ABOUT US
as well as the Java HotSpot VM. It JDK Versions with Complete limiting, because although native CLHSDB, which is a command-

is a snapshot debugger and lets SA Binaries debuggers can help us examine line variant of HSDB
us look at the state of a frozen The following JDK versions have the native OS process state, they HSDB: The GUI debugger. HSDB
Java process or a core file. When complete SA binaries: cannot help us examine the Java facilitates examining Java pro-
SA is attached to a Java process, JDK 7 on all platforms or the Java Virtual Machine (JVM) cesses, core files, and also remote
it stops the process at that point 6u17+ on Oracle Solaris and state of the process. Java processes. Lets see how
and we can explore the Java heap; Linux For example, if I need to view we can launch and use it on a
look at the threads that were run- 6u31+ on Microsoft Windows the objects in the Java heap, Microsoft Windows machine.
ning in the process at that point; Prior to these versions, SA was native debuggers would show me First, we need to set some envi-
examine internal data structures not shipped with the raw hex numbers, ronment variables. Set SA_JAVA to
of the Java HotSpot VM; and look the JDK on Microsoft DETAILS, DETAILS whereas SA has the the location of the Java executable
at the loaded classes, compiled
code of methods, and so on.
Windows, and only a
subset of SA classes
SA makes it very easy ability to interpret
those hex numbers
in the JDK/bin folder, for example:

The process resumes after SA is was shipped with JDKs to examine the and present the set SA_JAVA=
detached from it. on Oracle Solaris and Java-level details object view instead. d:\java\jdk1.7.0_03\bin\java
blog
SA Binaries
Linux. The JDK ver-
sions above make the
and JVM-level SA has knowledge
about the Java heap, On Microsoft Windows, the
Before we go into the details complete set of SA details of a Java such as its boundar- PATH environment variable should
about the features and utilities classes available on all process or core file. ies, objects in the Java contain the location of the JVM
that SA offers, I would like to men- of these platforms. heap, loaded classes, binary used by the target pro-
40
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
cess or core and also the folder where to the Java executable and then we can which are shown in Figure 2. We need to set the same environ-
the Debugging Tools for Windows are launch HSDB as follows: Figure 3 shows the Object Inspector, ment variables for CLHSDB as we did for
installed on the machine, for example: which you can use to inspect Java objects. HSDB. Use the following command to
java -Dsun.jvm.hotspot.debugger. Figure 4 shows how you can find launch this tool on Microsoft Windows:

JAVA IN ACTION
set PATH= d:\java\jdk1.7.0_03\bin\ useProcDebugger=true -classpath where a particular address lies in the
server;d:\windbg;%PATH% /java/jdk1.7.0/lib/sa-jdi.jar Java process. java -Dsun.jvm.hotspot.debugger.
sun.jvm.hotspot.HSDB Figure 5 shows the Object Histogram. useWindbgDebugger=true -classpath
Set the PATH environment variable You can find the heap boundaries, as d:\java\jdk1.7.0_03\lib\sa-jdi.jar
and then launch HSDB as follows: These launch commands bring up the shown in Figure 6. sun.jvm.hotspot.CLHSDB
HSDB GUI tool, as shown in Figure 1. CLHSDB: The command-line debugger.
java -Dsun.jvm.hotspot.debugger. Lets take a quick look at some of the CLHSDB is the command-line variant CLHSDB offers almost all the features
useWindbgDebugger=true -classpath very useful utilities available in this tool, of HSDB. that the GUI version of the tool offers.

JAVA TECH
d:\java\jdk1.7.0_03\lib\sa-jdi.jar
sun.jvm.hotspot.HSDB

On an Oracle Solaris or Linux


machine, we just need to set SA_JAVA

ABOUT US
Figure 1
Figure 3 Figure 5

blog

Figure 2 Figure 4 Figure 6


41
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6
For example, to examine any Java object,
hsdb> inspect 0x23f50a20
use the inspect command, as shown in
instance of Oop for java/lang/Thread @ 0x23f50a20 @ 0x23f50a20 (size = 104)
Listing 1.
_mark: 1
To look at heap boundaries, we can _metadata._klass: InstanceKlass for java/lang/Thread @ 0x38966700 Oop @

JAVA IN ACTION
use the universe command, as shown in 0x38966700
Listing 2. name: [C @ 0x23f50ac0 Oop for [C @ 0x23f50ac0
Listing 3 and Listing 4 show the com- priority: 5
plete list of commands available with threadQ: null null
eetop: 4758528
this tool.
single_step: false
daemon: false
Other Tools stillborn: false
There are some other very handy small target: null null
GIVE BACK!

JAVA TECH
utilities bundled with SA. Lets see how group: Oop for java/lang/ThreadGroup @ 0x23f50840 Oop for java/lang/Thread-
to use them and how their output looks: Group @ 0x23f50840
FinalizerInfo prints details on the contextClassLoader: Oop for sun/misc/Launcher$AppClassLoader @ 0x23f7b398 Oop
for sun/misc/Launcher$AppClassLoader @ 0x23f7b398
ADOPT A JSR
finalizable objects, as shown in
inheritedAccessControlContext: Oop for java/security/AccessControlContext @
Listing 5.
0x23f50ad8 Oop for java/security/AccessControlContext @ 0x23f50ad8
HeapDumper dumps the heap in
threadLocals: Oop for java/lang/ThreadLocal$ThreadLocalMap @ 0x23f7c960 Oop
HPROF format, as shown in Listing 6. for java/lang/ThreadLocal$ThreadLocalMap @ 0x23f7c960
PermStat prints the permanent gen- inheritableThreadLocals: null null Find your JSR here

ABOUT US
eration statistics, as shown in Listing 7. stackSize: 0
PMap prints the process map of the nativeParkEventPointer: 0
tid: 1
process (see Listing 8), much like the
threadStatus: 5
Oracle Solaris pmap tool does.
parkBlocker: null null
SOQL, the Structured Object Query
blocker: null null
Language tool, is an SQL-like lan- blockerLock: Oop for java/lang/Object @ 0x23f50ab8 Oop for java/lang/Object @
guage that we can use to query the 0x23f50ab8
Java heap, as shown in Listing 9. JHat uncaughtExceptionHandler: null nullCheck heap boundaries
also provides an interface for using
this language, and pretty good docu-
mentation on this language is also Download all listings in this issue as text
available in JHat.
JSDB, the JavaScript Debugger, pro-

vides a JavaScript interface to SA Lets Get Our Hands Dirty that follows it in the Java heap. This
(see Listing 10). It is a command-line Lets get a real feel for the SA tools and causes the program to crash when the
JavaScript shell based on Mozillas debug a Java program crash using them. garbage collector tries to scan the heap. blog
Rhino JavaScript engine. More details I have a simple program of Java Native See Listing 11.
on this utility can be found in the open Interface (JNI) code that writes to a byte The crash happened in
source Java HotSpot VM repository in array beyond its size limit, which results objArrayKlass::oop_follow_
the file hotspot/agent/doc/jsdb.html. in overwriting and corrupting the object contents(oopDesc*) at program counter
42
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
LISTING 7 LISTING 8 LISTING 9 LISTING 10 LISTING 11 LISTING 12

java -Dsun.jvm.hotspot.debugger.useWindbgDebugger=true -classpath d:\java\


jdk1.7.0_03\lib\sa-jdi.jar sun.jvm.hotspot.tools.PermStat 5684
Attaching to process ID 5684, please wait...
Debugger attached successfully.

JAVA IN ACTION
Client compiler detected.
Figure 9 JVM version is 22.1-b02
10713 intern Strings occupying 802608 bytes.
finding class loader instances ..
done.
computing per loader stat ..done.
please wait.. computing liveness..............................................done.
Figure 7
class_loader classes bytes parent_loader alive? type

JAVA TECH
<bootstrap> 342 1539808 null live <internal>
Figure 10 0x23f7b398 3 28016 0x23f762e0 live sun/misc/Launcher$AppClassLoader
@0x38a0e9c0
0x23f762e0 0 0 null live sun/misc/Launcher$ExtClassLoader@0x389
eb420

total = 3 345 1567824 N/A alive=3, dead=0 N/A

ABOUT US
Figure 11

see the contents of the registers and


Figure 8 what the value of the EAX register was:

(PC) 0xfe5d2c17. See Listing 12, which EAX=0x6e4f6176, EBX=0xc50a083c,


shows the stack trace of the crash from ECX=0x614a2e2e, EDX=0x00000006
the hs_err file. ESP=0xfbc7e360, EBP=0xfbc7e398,
With the crash, a core file got gener- ESI=0xc5036ef0, EDI=0x00000000
ated. Lets open this core with HSDB (see EIP=0xfe5d2c17, EFLAGS=0x00010202
Figure 7), dig out some information from
it, and try to find the cause of this crash. What was at 0x6e4f6176, and why
Figure 8 shows the disassembly of the did the crash happen while reading the Download all listings in this issue as text
code that was being executed around PC value at this address? HSDB helps us see
0xfe5d2c17 when the crash happened. that, as shown in Figure 9. blog
The instructions shown in Figure 8 The address does not lie in the Java address is referenced (see Figure 10). All the found addresses bring up the
indicate that the process crashed when heap. Using the Find Address in Heap Examine these found locations in the byte array object at 0xc5036ea0 in the
trying to access the value at address option, we can find the locations in the Object Inspector to see if these are part Object Inspector, which means the
eax+100. From the hs_err file, we can Java heap from which this particular of any object, as shown in Figure 11. object at 0xc5036ea0 is the closest valid
43
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
LISTING 13 LISTING 14

(dbx) x 0xc5036ea0/100c
0xc5036ea0: '\001' '\0' '\0' '\0' '\030' '\0177' '\020' '' '\003' '\0' '\0' '\0'
'H' 'e' 'l' 'l'

JAVA IN ACTION
0xc5036eb0: 'o' ' ' 'J' 'a' 'v' 'a' '.' 'H' 'e' 'l' 'l' 'o' ' ' 'J' 'a' 'v'
0xc5036ec0: 'a' '.' 'H' 'e' 'l' 'l' 'o' ' ' 'J' 'a' 'v' 'a' '.' 'H' 'e' 'l'
0xc5036ed0: '\003' '\0' '\0' '\0' 'a' 'v' 'a' '.' 'H' 'e' 'l' 'l' 'o' ' ' 'J' 'a'
0xc5036ee0: 'v' 'a' '.' 'H' 'e' 'l' 'l' 'o' ' ' 'J' 'a' 'v' 'a' '.' 'H' 'e'
0xc5036ef0: 'l' 'l' 'o' ' ' 'J' 'a' 'v' 'a' '.' 'H' 'e' 'l' 'l' 'o' ' ' 'J'
0xc5036f00: 'a' 'v' 'a' '.'
YOUR
Download all listings in this issue as text
LOCAL JAVA
USER GROUP

JAVA TECH
NEEDS YOU
starting at 0xc5036eb0.
This gives us a big clue. Now, we can
easily search in the code where the bytes
Hello Java.Hello Java. . . are being writ-
ten, and find the buggy part of the code
Find your JUG here
that overflows a byte array. Listing 14

ABOUT US
shows the faulty lines that I had in my JNI
code. Wow! This was so easy.

Summary
Figure 12 As in the example above, we in the JVM
Sustaining Engineering Group at Oracle
object just before these locations. If we use the Serviceability Agent on a daily
look carefully, these locations actually basis to debug crashes, hangs, and other
go beyond the limits of the byte array kinds of problems that occur with the
object, which should end at 0xc5036eb0, Java HotSpot VM. SA is a pretty useful
and from address 0xc5036eb0, the and powerful debugging tool that can
next object should have started. See also help you learn the internals of the
the raw contents at memory location Java HotSpot VM. I hope this article pro-
0xc5036ea0 in Figure 12. vided good insight into this tool. Enjoy
We can look at the raw contents as debugging with SA! </article>
characters in the dbx debugger. See blog
Listing 13, which clearly shows that the
object at 0xc5036ea0 has a byte stream
that goes beyond its size limit of three LEARN MORE
elements and overwrites the object SA-Plugin for VisualVM
44
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
Fork/Join Framework for
Client Java Applications

JAVA IN ACTION
Java SE 7s fork/join framework makes a great match for CPU-intensive client-side applications.
JOSH MARINACCI

C PUs arent getting faster. desktop apps need help with CPU- if you dont know dual-core laptops
BIO
ALGORITHM AT WORK

JAVA TECH
Nearly ten years ago, we hit bound tasks as well. the scope of the and single-core
3 GHz and I have yet to own a It is far harder to make CPU- work beforehand. Every class that phones, as well as the
4 GHz machine, much less the bound tasks maximize your Fork/join provides uses the fork/join 100-core desktop of
43 GHz Moores Law promised computer, especially on a general- work-stealing framework works the future.
me. CPUs can do far more than purpose operating system where behavior that can
they used to, but they do it by many other processes vie for CPU better balance the
with pretty much Something Simple
getting wider instead of faster time. To help with this, Java SE 7 workload across this algorithm: If the To see how the fork/
more CPUs with more cores with introduced a new framework to multiple proces- amount of work is join framework works,

ABOUT US
more threads.
While this is great for the end
the concurrency utilities that can
help with CPU-bound tasks: the
sors, and with less
lock contention.
below a threshold, lets try something
simple. Every class
user, it introduces new challenges fork/join framework. Traditional algo- then do the work; that uses the fork/join
for application developers. I can The fork/join framework in Java rithms can max out otherwise, split framework works with
buy a 12-core desktop from Apple,
and even my small laptop has 2
SE 7 is conceptually pretty simple.
You fork the current thread to
at about eight pro-
cessors before the
the work in half and pretty much this algo-
rithm (see Listing 1):
cores now. The world is becoming divide up your work, and then you overhead of lock recurse, waiting If the amount of work
parallel, so we need new ways to join the tasks back together to contention out- for each half to is below a threshold,
code for parallel machines.
Java has always had good sup-
collect the finished results. As we
will see below, coding with this
weighs the speed of
using more cores.
complete. then do the work;
otherwise, split the
port for concurrent programming new framework is pretty easy. The Fork/join can scale work in half and
thanks to java.lang.Thread. The value of fork/join is what it does to over 100 cores. recurse, waiting for
Thread class has existed since the under the hood. Fork/join is future- each half to complete.
first release of J2SE 5.0 introduced proof and portable. The code This is the textbook divide-and-
the ExecutorService to ease the Fork/Join Framework you write with it doesnt conquer method.
management of groups of threads. The fork/join framework provides assume anything about the To demonstrate how this works blog
Unfortunately, threads mainly three benefits over the Executor underlying hardware. Its in practice, Ive created a simple
help with I/O-bound tasks. Thats interface. designed to run your code as example that calculates the mini-
fine for server-side jobs, such as Fork/join is a natural fit for a efficiently as possible across mum number from a very large
PHOTOGRAPH BY
CHRIS PIETSCH/GETTY IMAGES hosting Web apps, but modern recursive algorithm, especially any hardwareboth todays array of doubles (see Listing 2).
45
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
LISTING 1 LISTING 2
The compute method in Listing 2 it again with two cores and repeated that
compute() {
implements the algorithm I described in six times. By duplicating and averaging, I
if ( work.size < threshold ) {
Listing 1. If the number of doubles to be can ensure that I get reliable results.
return doWork(work);
searched is less than a threshold (100), You can see in Figure 1 that the single- } else {

JAVA IN ACTION
then calculate the minimum; otherwise, core time hovers around 190 ms and the f1 = fork(first half of work)
recurse on each half and wait for them dual-core time hovers around 122 ms, f2 = fork(second half of work)
to join (complete). Once you have the which means that two cores take only wait for the forks to join
result of each half, calculate the mini- 64 percent of the single-core time. The }
}
mum of those and return it. improvement is not quite the double
The MinimumFinder class implements that we might hope for when using two
the RecursiveTask<Double> interface, cores, but its pretty good.
which is one of two interfaces defined Why werent the dual-core results

JAVA TECH
by the fork/join framework. The other exactly twice as fast (95 ms)? There are
interface, RecursiveAction, is identical a few reasons. First, there is overhead
except that its compute method doesnt involved in using the fork/join frame-
return anything. work. For small tasks, its simply not
The magic is in the join() method. It worth the overhead. Unfortunately, most
will wait for the subtasks to complete. tasks for which its worth the overhead
Figure 1 shows a simple benchmark of are also too complicated to use as exam-
the time it takes to search through 30 ples, which is why many of the fork/join

ABOUT US
million random numbers using a single tutorials on the Web demonstrate some-
core or the two cores on my laptop. I thing like calculating the Fibonacci series.
calculated the average over 10 runs for a Calculating the Fibonacci sequence with
single core, and then switched to doing recursion is actually a horrible example
because its not very efficientyou wont
get a 2x speedup, and there are much
better nonrecursive ways to do it faster.
That said, how could we improve
this demo to better show the value of
multicore? Lets make the algorithm do
more work so that the fork/join over-
Figure 1 head is less of a factor. I kept the same
code but added a line that does three
multiplications per value in the array.
Because multiplication is much slower
than comparisons, this should increase blog
the calculation time a lot. Figure 2 shows
the results of the next run, now slow
enough to take nine minutes on my Download all listings in this issue as text
Figure 2 laptop for the entire run.
46
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
The dual-core version takes about 55 with pixels that never escape. This
percent of the time that the single-core means they each went through the
version takes. Thats within about 10 loop the same number of times (to the
percent of perfect efficiency, and it con- threshold), so the work required to cal-

JAVA IN ACTION
stantly pegs my CPU. Excellent! culate those pixels is always the same.
This example is fine for learning the The colored pixels, however, escaped
API, but what could we actually do with sometime before the limit. This means
this in the real worldespecially when that these pixels required less work than
it comes to client-side applications? The the maximum amount. Of course, the
first thing that comes to mind is graph- black pixels are boring. Its the varying
ics. A lot of complex graphics rendering colored pixels that are interesting, so
is very easy to make parallel. Lets take a the part we want to look at has the most

JAVA TECH
look at one of the most common CPU- varied workload. The fork/join frame-
intensive kinds of graphics: fractals. work is the perfect way to parallelize this Figure 3 Figure 4
workload efficiently.
Parallel Mandelbrot Graphics A regular parallel algorithm for the a fixed thread pool versus the fork/join Oracles concurrency expert, Brian
The Mandelbrot set is often consid- Mandelbrot set would divide the picture framework. Figure 4 is a graph of the Goetz, explains it this way:
ered the classic fractal or at least the into rows of pixels, allocating a thread results of the fixed thread pool versus If youve got a problem of size N
most widely known. Every pixel in the for every set of rows. So what would hap- the fork/join framework for a 4,000 x with p processors, when you divide
Mandelbrot set can be calculated inde- pen if one set of rows happened to take 4,000 pixel fractal. into problems of size N/p you are sure

ABOUT US
pendently of the others, which makes it longer than the other set? This will hap- We can loosely group workloads into to get lumpiness. Some will finish first
a great target for parallel computation. pen if one row in the fractal has more two categories: smooth and lumpy. and those CPUs will then be idle. If you
It also has another inter- black in it than another. With a smooth workload, all units of make subproblems of, say, N/10*p, the
esting attribute: the work PERFECT FIT If we used a regular work take about the same effort (time) single work queue becomes a sequential
isnt smooth. To calculate a
pixel in the fractal, you run
Fork/join is a natural
thread pool, one of the
threads would be done
to complete, whereas lumpy workloads
take variableoften highly variable
bottleneck as multiple threads contend
for get next chunk of work. Even if your
a simple equation over and fit for a recursive before the others and would amounts of effort. You can see this effect problem is evenly balanced to start,
over again until the value algorithm, especially if
just sit around being idle. in Figure 4. While both versions are things like cache misses, page faults,
exceeds a certain threshold. you dont know the scope
A fork/join thread pool faster when using two cores, the fork/ GC, etc., will cause different ones to run
This is called escaping. The of the work beforehand.
wouldnt, however, because join version finishes faster than the pool at different rates. You get lumpiness.
color of the pixel is based of a very unique property: version. The pool version is only a tiny Fork/join says: rather than sweating the
on how many times through work stealing. If one of the bit faster with two cores than with one lumpiness, let work stealing iron it out
the loop it took for the threads is idle because it core because the work is lumpy. On a for you.
value to escape. If the loop goes on long has finished its work, it can steal some two-core machine, the first thread fin- A quick note on this example. I am
enough (another threshold value), then work from another thread. The frame- ishes three times faster than the second using a buffered image to store the
we can say that the pixel never escapes work will automatically load balance thread, but because it is a fixed pool, pixels. Each loop would call image.setRGB blog
and mark it as black. Figure 3 shows a across the set of threads, making sure you are limited by the time of the slow- for each result pixel. Commenting out
classic Mandelbrot set fractal. its always crunching on something and est thread. The fork/join version doesnt the image.setRGB line speeds up my test
Take a look at this picture of the maximizing the CPUs. have this problem with lumpy workloads of even the single-core version from
Mandelbrot set. The center part is filled Lets look at the Mandelbrot set using thanks to work stealing. an average of 5,000 ms to 3,900 ms.
47
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
Something in the way buff- IMAGE HANDLER perform lots of additional
ered images work is very slow processing to find human
compared to just setting an The new fork/join faces, look for object edges,
array value. This shows that framework is a and do many other things; so
great match for

JAVA IN ACTION
the things we think are slow its good to have fast image
arent always the culprit. In segmentation.
this case, I could improve the CPU-intensive One simple form of image
general code performance a
lot by using an array of inte-
client-side
applications,
segmentation uses a quadtree
graph. To segment the image, YOUR
LOCAL JAVA
gers and then converting to you start by looking at a large
an image after the work is such as image square section of the image
done. The lesson here is that manipulation and (usually the entire image)

USER GROUP

JAVA TECH
we must always profile our and determine if the pixels
code to figure out where it is image generation. in that square are similar

NEEDS YOU
really slow. enough using a threshold
value. If so, then the square
Image Segmentation can be represented with a
For a final example, I chose something single color value. If they are not similar
a little bit different: image segmenta- enough (which is most likely, initially),
Find your JUG here
tion. Many algorithms in image process- then subdivide the square into four

ABOUT US
ing, from compression to computer smaller squares and repeat. Eventually,
vision, begin with the step of dividing this recursive algorithm will reach small
the image into chunks that are simi- enough squares so that the pixels within
lar. This is called image segmentation. are similar, or you reach a square the
Once an image is segmented, you can size of a single pixel (which of course is
similar to itself). The resulting graph of
nested squares is called a quadtree (the
three-dimensional version of it is called
an octree).
Figure 5 shows an image with the
quadtree graph overlaid on top. You can
see that there are more small squares in
the parts with more detail.
Some of the squares in the quadtree
will be larger than others, because
that part of the image had more simi- blog
lar pixels. The parts of the image with
more different pixels will have smaller
squares and will be deeper in the graph.
Figure 5 This means the graph construction
48
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
LISTING 3
threading. See Figure 6, which shows the
The following listing has been excerpted for space, as noted by the . . . symbol. The full
runtimes with different thread counts.
code listing is available by downloading the code listings for this issue.
You can see that the speedup between
a single thread and two threads is quite public class Node {

JAVA IN ACTION
significant. It doesnt speed up after ...
that, of course, because I have only two protected void compute() {
physical cores. However, it doesnt slow if(w <= 1 || h <= 1 || measureDetail(grid,x,y,w,h) <= threshold) {
down much either. This shows that the color = average(grid,x,y,width,height);
} else {
fork/join framework can do its job with
children[0] = new Node(grid,x,y,w/2,h/2,threshold);
minimal overhead. children[1] = new Node(grid,x+w/2,y,w-w/2,h/2,threshold);
children[2] = new Node(grid,x,y+h/2,w/2,h-h/2,threshold);
Conclusion children[3] = new Node(grid,x+w/2,y+h/2,w-w/2,h-h/2,threshold);

JAVA TECH
The fork/join framework doesnt actu- invokeAll(children);
Figure 6 ally make the Java Virtual Machine run }
faster. It simply presents a more con- }
Color average(int[][] grid, int x, int y, int w, int h) {
process will be lumpy. Some parts of venient way to express parallel algo-
int redSum = 0; int greenSum = 0; int blueSum = 0;
the image will take longer to process rithms so that your code can run more int area = w*h;
than others, using more CPU. Most efficiently than if you had to split it up by for(int i=x; i<x+w; i++) {
importantly, we dont know beforehand hand. The real point of fork/join is that for(int j=y; j<y+h; j++) {
which parts of the image will take lon- you have to worry only about your algo- redSum += getRed(grid[i][j]);

ABOUT US
ger, so we cant evenly divide the work rithm, not how its implemented. Your greenSum += getGreen(grid[i][j]);
blueSum += getBlue(grid[i][j]);
among CPUs without the work-stealing code could run on one core or a hun-
}
behavior of the fork/join framework. dred, and you dont have to care. The
}
So, image segmentation boils down to system will maximize efficiency for you, return new Color(redSum/area,greenSum/area,blueSum/area);
recursive graph construction comparing now and in the future. This makes the }
lumpy image data to a threshold value. new fork/join framework a great match int measureDetail(int[][] grid, int x, int y, int w, int h) {
Sounds perfect for fork/join. for CPU-intensive client-side applica- Color avg = average(grid, x, y, w, h);
Take a look at Listing 3 to see a demo tions, such as image manipulation and int red = avg.getRed(); int green = avg.getGreen(); int blue = avg.getBlue();
int area = w * h; int colorSum = 0;
app and performance tests. I adapted image generation. </article>
for(int i=x; i<x+w; i++) {
this example from the code presented for(int j=y; j<y+h; j++) {
in this Dev.Mag article. I dont include colorSum += Math.abs(red-getRed(grid[i][j]));
the code for the entire project; I provide colorSum += Math.abs(green-getGreen(grid[i][j]));
just the interesting parts. As a side note, LEARN MORE colorSum += Math.abs(blue-getBlue(grid[i][j]));
it only took about five minutes to paral- }
Josh on Design
lelize the original code. The fork/join }
Fork/join framework return colorSum / (3 * area);
framework plays very nicely with recur- blog
Showtime! Java 7 Is Here! }
sive algorithms.
I ran this app on my dual-core laptop Meet JavaMan
(with a larger 2,000 x 3,000 test image) Fork and Join: Java Can Excel at Painless Download all listings in this issue as text
set to run with different amounts of Parallel Programming Too!
49
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
How to Modify javac
Learn the steps for changing javac to implement new language syntax features.

JAVA IN ACTION
F or Java developers who want
to work with the language and
platform they love, the last two
members of the Java commu-
nity that are not already directly
involved in the OpenJDK, such as
simple new language syntax fea-
ture, the Elvis operator. It high-
lights some of the technical steps
add features to Java. This process
is performed in three distinct
phases, as shown in Figure 1. Well
years have been groundbreaking Oracle, Red Hat, IBM, and many that you would take if you were to just give you a quick overview
ones. Java SE 7 was released after a others), while keeping in mind a tackle one of the more advanced of the three compilation phases

JAVA TECH
long five-year wait andcrucially do no harm policy. projects in the Adopt OpenJDK here; for more details, see the
for developers interested in Java Flooding the OpenJDK project program. Of course, to add a lan- OpenJDK documentation.
and the Java Virtual Machine with thousands of patches a week guage feature, you also would have Parse and Enter phase. As a first
(JVM) itselfthe OpenJDK and demanding acceptance of to fulfill the requirements of the step, the javac lexer reads the Java
project became the Reference ill-thought-out language features OpenJDK process by submitting a source files (as an input stream of
Implementation (RI) for Java. would not make for a better Java. JDK Enhancement Proposal (JEP). characters) and maps these into
In addition to the RI code base For the Adopt OpenJDK program, a sequence of tokens. The parser
becoming fully open source, great doing no harm means producing Overview of Compilation takes these tokens and gener-

ABOUT US
progress was made in simplifying well-thought-out, peer-reviewed Using javac ates Abstract Syntax Trees (ASTs)
the complex build process, and bug fixes and new features that The Java compiler, javac, takes representing the source program.
most developers are now able to are backed by empirical evidence a set of Java source files (.java) These trees are made of AST
build the OpenJDK with a simple and coordinated with the core as input and produces the cor- nodes that represent the differ-
RAOUL-GABRIEL URMA, one-line command. OpenJDK committers. responding .class files as output. ent constructs in the source code,
JANINA VOIGT, AND Last, the existing OpenJDK Why such a formal/strict You need to understand the basics such as method declarations,
MARTIJN VERBURG committers continued their out- approach? The OpenJDK is of javac compilation in order to statements, and so on.
reach to the wider Java commu- now the heart of a vital piece of
BIO
nity, encouraging participation. technology that (in application
Today, the OpenJDK is more open software terms) runs large parts
than ever and the barriers to entry of our entire civilization, affect-
Annotation
have been significantly lowered. ing billions of people daily. So, Parse Enter Processing
In late April 2012, the London changes to it need to be made .java files
Java Community launched the with a great deal of care and
Analyze Generate
Adopt OpenJDK program. This with as much scientific rigor and Attribution
program is a group of projects empirical analysis as possible. Flow Analysis blog
Generics
and events led by Java user groups Thats not to say that the .class files Desugaring
(JUGs) that aims to channel into day-to-day developer cant get
the OpenJDK the efforts of the involved, and this article takes you
MARTIJN VERBURGS
PHOTOGRAPH BY BOB ADLER wider Java community (those through implementing a relatively Figure 1
50
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
For example, consider the simple type checking is performed, and able is null. As explained in Elvis and 3. Go to the command line (or your
expression 2 + 2 * 5. We can repre- constant expressions are simpli- Other Null-Safe Operators, it is a binary Mercurial GUI client).
sent this expression as the AST shown fied (a process known as constant operator and results in the value of the 4. Enter the following command:
in Figure 2. The tree structure makes folding). Many semantic errors can left-hand side if it is not null, avoiding

JAVA IN ACTION
it clear how (and in what order) the be discovered during this phase, evaluation of the right-hand side. If the hg clone http://hg.openjdk.java.
expression is evaluated. including type errors and missing left-hand side is null, the right-hand side net/jdk8/tl/langtools <dir>
Once the parser has generated ASTs, symbols. is evaluated and is the result.
any symbols defined by the program are 2. Flow analysis: The javac compiler For example, suppose we have a Once the code has been cloned into
entered into the symbol table. For each checks that all statements are reach- String foo: the <dir> directory, do the following:
class, all symbols defined by the class able and performs exception analysis 1. Enter the following command:
are entered into the class scope. to ensure that every checked excep- foo ?: "default"
Annotation Processing phase. In the tion that is thrown is either declared cd <dir>/make

JAVA TECH
second phase, any annotations in the or caught. It also analyzes assign- It returns the String value stored in
program are processed by calling the ments to ensure that each variable foo if foo is not null; otherwise, it returns 2. Edit the build.properties file and set
relevant annotation processors. Each is assigned a value before it is used default. boot.java.home to an installation of
annotation processor is loaded and run and that final variables are assigned Using the existing ternary operator the JDK you already have.
in a separate class loader. It is possible values only once. (which has a very similar syntax), the 3. Enter the following command:
that running an annotation processor 3. Generics: Code that includes generics previous statement is equivalent to this:
generates additional source files; if this is translated into code without gener- ant
happens, the Parse and Enter phase ics to comply with type erasure. (foo != null) ? foo : "default"

ABOUT US
might need to be repeated. 4. Syntactic desugaring: The javac The build should complete with a
Analyze and Generate phase. Next, compiler rewrites the syntax trees to The Elvis operator is available in message similar to the following:
javac analyzes the ASTs before generat- remove syntactic sugar, such as inner several other JVM languages, including
ing .class files. The analysis of the ASTs classes, assertions, and for-each Groovy and Scala, but not in Java itself. BUILD SUCCESSFUL
entails the following steps: loops. It was proposed as an addition to JDK 7 Total time: 1 minute 2 seconds
1. Attribution of ASTs: Names and If all the checks above pass, javac as part of Project Coin but was not
expressions in the ASTs are resolved, generates .class files containing included in the final feature selection. As Modifying the Java Compiler
Java bytecode. we noted earlier, adding even seemingly The implementation of the Elvis opera-
simple language features needs to be tor in the Java language requires several
* Adding the Elvis weighed carefully. steps:
Operator to Java 1. Modify the lexer so that it recognizes
In this section, well show Building the Java Compiler the Elvis operator.
you, step by step, how to Building javac is fairly simple. Visit the 2. Modify the parser so that it generates
+ modify javac to imple- OpenJDK compiler group for an over- an AST node representing the Elvis
5
ment the Elvis operator. view. Weve distilled the steps below: operator.
The Elvis operator, ?: 1. If it is not already installed, install a 3. Provide a translation of the Elvis oper- blog
2 (look at it sideways to see Mercurial DVCS client for your operat- ator in Java bytecode.
2 where it got its name), ing system. However, this process can be simpli-
is useful for returning a 2. If it is not already installed, install the fied slightly because the Elvis operator
Figure 2 default value when a vari- ANT build tool. can be converted to an existing language
51
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3
feature: the ternary operator. Therefore, token, typically using the default
public enum Token implements Formattable {
we can just modify the parser so it gen- implementation that lies in com.sun
EOF,
erates a ternary operator AST node. We .tools.javac.parser.Scanner
ERROR,
can then rely on the translation phase Parser modification. We now modify ...

JAVA IN ACTION
to recognize this node and translate it the Java parser so that it recognizes QUES("?"),
to correct Java bytecode without provid- expressions of the form Expression1 ?: ELVIS("?:"), // <---
ing our own translation implementation Expression2. The implementation for this COLON(":"),
(this process is called AST translation). is defined in com.sun.tools.javac.parser ...
}
Lets begin with the first step, the lexer .JavacParser.
com.sun.tools.javac.parser.Token
modification. Theres a method in JavacParser called
Lexer modification. First, lets add the parseExpression(), which parses expres-
Elvis operator so it is recog- sions. It processes the token

JAVA TECH
nized as a new token. We do stream it gets from the Java
BIG IMPACT
this by modifying the com.sun lexer and returns AST nodes
.tools.javac.parser.Token class, The OpenJDK is as output.
inserting the Elvis operator now the heart Each AST node is a subclass
as a new token value. See
Listing 1.
of a vital piece of com.sun.tools.javac.tree
.JCTree. Since parseExpression()
All the tokens are auto- of technology deals only with expressions,
matically added to a keyword that (in application
it outputs a JCExpression (a

ABOUT US
table, which is defined in the subtype of JCTree) that rep-
com.sun.tools.javac.parser software terms) resents expression nodes.
.Keywords class. The Keywords runs large parts Other kinds of nodes are rep-
class maps all token names
(the value passed into the
of our entire resented by other subclasses
of JCTree. For example, state-
Token constructor) to their civilization, ment nodes are represented
Token instance. affecting billionsby JCStatement.
The keyword table is then
used by the Java lexer to map
of people daily. The TreeMaker class is
a factory for AST nodes; Download all listings in this issue as text
an input stream of characters JavacParser has a field called F
into a token sequence. The of type TreeMaker that we can
lexer interface is specified in use in our code to easily cre- between assignment expressions and course, both of the sides can be made
com.sun.tools.javac.parser.Lexer and it ate various kinds of AST nodes. other types of expressions. For example, of subexpressions. For all other kinds of
contains various methods, such as the The parseExpression() method is x = 1 and x /= 5 are assignment expres- expressions, all the parsing is delegated
following: defined as shown in Listing 2 and essen- sions; x++ counts as another expression. to term1(), which well look at more
pos(), which returns the current posi- tially sets the parser mode to expect If term() discovers an assignment closely now. blog
tion of the lexer expressions (EXPR). It then calls term() operator in the expression, it parses the The term1() method is defined as
nextToken(), which reads the next to parse and create expression nodes of left-hand side and the right-hand side shown in Listing 3.
token type JCExpression. of the assignment separately by first We can see that term1() delegates
token(), which returns the current The term() method distinguishes calling term1() and then termRest(); of most of its work to yet another helper
52
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//java architect /

COMMUNITY
LISTING 4 LISTING 5 LISTING 6 LISTING 7 LISTING 8
method, term2(). Fortunately for us, nodes representing the left-hand side
JCExpression term1() {
we wont need to look more closely at and right-hand side of the expression.
JCExpression t = term2();
term2() here, because term1() handles The final implementation of
if ((mode & EXPR) != 0 && S.token() == QUES) {
the parsing of the ternary operator. If term1Elvis() is shown in Listing 5. mode = EXPR;

JAVA IN ACTION
term1() finds a question mark token Now that youve finished the imple- return term1Rest(t);
(QUES), it knows its dealing with a ter- mentation, rebuild the javac compiler, }
nary operator. The first part (before the per the Building the Java Compiler else if ((mode & EXPR) != 0 && S.token() == ELVIS)
question mark) has already been parsed section. Congratulations; you can now {
mode = EXPR;
by term2(); the remaining two parts use the Elvis operator in your code with
return term1Elvis(t);
(before and after the colon) are then your shiny new Java compiler!
}
parsed by term1Rest(). else {
The Elvis operator is very similar to Testing return t;

JAVA TECH
the ternary operator, so term1() is a good Of course, as with any software, we need }
place to parse it. So if we find an Elvis to ensure that theres some level of test- }
token here, we parse the expression as ing. (Some would argue we could have
an Elvis operation, as shown in Listing 4. used test-driven development here,
Our task now boils down to pro- but we were influenced by Martijn, the
viding the implementation for Diabolical Developer.)
term1Elvis(JCExpression). As explained So, lets write a basic test to see if
previously, we can simply convert an the Elvis operator works as desired. See

ABOUT US
Elvis operation into a ternary operation. Listing 6.
Thus, term1Elvis(JCExpression) should The code in Listing 6 should print the
parse the right-hand side of the expres- word unknown.
sion (which follows the ?: token) and Note that because we simply trans-
then create an AST node representing lated our Elvis operator into a ternary Download all listings in this issue as text
a ternary operation of the form expr1 != operator, we dont need to worry about
null ? expr1 : expr2. things like type checking. For example,
We already have an AST node for the the code in Listing 7 doesnt compile (as Qualitas Corpus) that this feature would University, U.K. They have embarked on
left-hand side of the Elvis operation expected). The error shown in Listing 8 be utilized by developers. The partici- several research topics related to Java
(passed as argument expr1). We then is reported. pants in the Adopt OpenJDK program and have joined the Adopt OpenJDK
parse the right-hand side by calling are there to help with all of that. program. They have very kindly made
term() and store this in expr2. Conclusion We hope you enjoyed this journey some of their research and methodology
The next step is to construct an AST Adding the Elvis operator is a fun exam- into javac, and we hope to see you in the available to share with fellow developers.
node representing the conditional ple of adding a small language feature at Adopt OpenJDK program working on the Its been a pleasure to collaborate on this
expression expr1 != null. Now we have the level of the javac compiler. If this was language and the platform that we all article with them; I certainly learned a
the three pieces that are required, so a serious attempt at getting this feature share. </article> great deal. Martijn Verburg blog
we can just create the ternary operation into the OpenJDK, you would have to
AST node. This is done by calling the apply more-rigorous proof that the code Raoul-Gabriel Urma and Janina Voigt
Conditional method of the TreeMaker and was correct and safe as well as providing are PhD students from the department
passing in the conditional node and the empirical evidence (such as using the of Computer Science at Cambridge
53
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//rich client /

COMMUNITY
Part 2
Lazy Evaluation, Lazy Initiation, and
Custom Bindings in JavaFX 2

JAVA IN ACTION
JAMES L. WEAVER Optimize the evaluation of bindings and the initialization of properties the lazy way.
BIO

J avaFX 2 is an API and run- javafx.beans.binding of this article, youll modify the As shown in Figure 3, when

JAVA TECH
time for creating rich internet javafx.beans.property code to implement the lazy you click the Start button on one
applications (RIAs). It was intro- javafx.beans.value evaluation, lazy initialization, of the stopwatches, its elapsed
duced in 2007, and version 2 was This article contains an example and custom binding behavior of timer starts counting by millisec-
released in October 2011. One of of using the methods defined by the LazyInitEvalSolution project, onds. In order to see the elapsed
the advantages of JavaFX 2 is that many of these interfaces to imple- which is also available in the file time, however, you must click the
the code can be written in the ment lazy evaluation, lazy initial- youll download. invalidate click to bind/unbind
Java language, using mature and ization, and custom bindings.
familiar tools.

ABOUT US
This article is Part 2 of a two- Overview of the
part series and focuses on opti- LazyInitEvalSolution
mizing JavaFX 2 properties and Application
binding by implementing lazy To help you learn how to use
evaluation, lazy initialization, and properties and binding, an
custom bindings. example application named
As discussed in the previous LazyInitEvalSolution will be
article, Using Properties and employed. As shown in Figure 2,
Binding in JavaFX 2.0: Part 1, this application contains three
JavaFX 2 comes with a set of inter- stopwatches, and each has
faces, which are shown in Figure 1. some buttons and elapsed and
The purpose of these interfaces is lap time displays.
to provide support for using and The LazyInitEvalExercise
implementing properties, detect- project that youll download
ing when the values of properties in the next section contains
have changed, and binding prop- starter code for the example blog
erties to other properties. application. In its current
These interfaces are located in form, the applications run-
four packages: time appearance is similar to
PHOTOGRAPH BY
STEVE GRUBMAN javafx.beans Figure 2. During the course Figure 1
54
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//rich client /

COMMUNITY
text. As youll see when we walk through displayed. You may also click the Stop displayed as an integer, rather than in tiates a SimpleStringProperty, binds it
the relevant code, this demonstrates the button to cause the elapsed time to minutes:seconds:milliseconds format. to the elapsedMillisProperty property of
concept of lazy evaluation. stop increasing, and you may click the This is because LazyInitEvalSolution the StopWatchModel class, and adds an
Also, when you click the Lap but- Reset button to reset both the elapsed uses a custom binding that youll imple- InvalidationListener to it.

JAVA IN ACTION
ton, the lap time at that moment is and lap times. ment in one of the steps below. As a result, when the value of elapsed-
Below are the steps you can follow TimeStrProperty is no longer valid, it isnt
Obtaining and Running the to implement all of the behavior in evaluated immediately; hence, the term
LazyInitEvalExercise Project LazyInitEvalSolution. lazy evaluation.
1. Download the NetBeans project
file, which includes the Step 1: Gain an
LazyInitEvalExercise program. Understanding of Lazy
2. Expand the project into a directory of Versus Eager Binding

JAVA TECH
your choice. Evaluation
3. Start NetBeans, and select File -> A binding can be evaluated
Open Project. in either an eager or a lazy
4. From the Open Project dialog box, manner:
navigate to your chosen directory and When a binding is evalu-

open the LazyInitEvalExercise project, ated in an eager man-


as shown in Figure 4. If you receive a ner, the updated value of
message stating that the jfxrt.jar file the binding is calculated Figure 4

ABOUT US
cant be found, click the Resolve but- whenever the binding is
ton and navigate to the rt/lib folder invalidated.
Figure 2 Figure 5
subordinate to where you installed When a binding is evalu-

the JavaFX 2 SDK. ated in a lazy manner, the


Note: You can obtain the NetBeans updated value of the bind-
IDE from the NetBeans site. ing is calculated only
5. To run the application, click the Run when needed.
Project icon on the toolbar, or press Take a look at the code in
the F6 key. The icon looks like the Play the StopWatchNode.java file
button on a DVD player, as shown in in the LazyInitEvalExercise
Figure 5. project, which shows the
The LazyInitEvalExercise application starter code for this example.
should appear in a window, as shown in Well show code snippets
Figure 6. from LazyInitEvalMain.java
The behavior of LazyInitEvalExercise as you perform the steps in
is different in a few ways from this exercise. blog
LazyInitEvalSolution. For example, as Implementing lazy evalua-
shown in Figure 6, clicking the Start but- tion in a binding. As shown in
ton and then clicking the invalidate Listing 1, some of the code in
Figure 3 text causes the elapsed time to be StopWatchNode.java instan- Figure 6
55
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//rich client /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5
Implementing eager evaluation in a tation of these methods causes the
private StringProperty elapsedTimeStrProperty = new SimpleStringProperty();
binding. As shown in Listing 2, when SimpleIntegerProperty to be instantiated
the user clicks the invalidate click to the first time that the lapMillis prop-
... code omitted ...
bind/unbind text, the textProperty of the erty is accessed via the setLapMillis(),

JAVA IN ACTION
elapsedNode is bound to the elapsed- getLapMillis(), or lapMillisProperty() elapsedTimeStrProperty.addListener(new InvalidationListener() {
TimeStrProperty. This causes the bind- method. This can be a waste of memory public void invalidated(Observable observable) {
ing to be evaluated in an eager manner, resources, depending on how the prop- if (!elapsedNode.textProperty().isBound()) {
because the elapsedNode (a Label con- erty is used in practice. Lets explore elapsedNode.setText(invalidated - click to bind/unbind);
}
trol) gets and displays the value of the ways to optimize this, beginning with
}
elapsedTimeStrProperty whenever it is half-lazy initialization.
});
invalidated. Implementing a half-lazy initializa-
By using a lazy evaluation strategy tion approach. As shown in Listing 4, elapsedTimeStrProperty.bind(stopWatchModel.elapsedMillisProperty()

JAVA TECH
when applicable, an application can the half-lazy initialization approach .asString());
avoid unnecessary process- avoids instantiating the
ing, often improving per- BEING LAZY IS GOOD SimpleIntegerProperty ref-
formance as a result. Lets
move on to another optimi-
By using a lazy erenced by lapMillis when
the getLapMillis() is called.
zation technique: lazy initial- evaluation strategy, It also avoids instantia-
ization of properties. an application can tion when the setLapMillis()
avoid unnecessary method is called with the

ABOUT US
Step 2: Implement Lazy lapMillis propertys default
Initialization of a Property processing, often value, which is held in
A JavaFX property can be improving DEFAULT_LAP_MILLIS.
initialized in either an eager
or a lazy manner. There are
performance. Go ahead and plug in the
code from Listing 4 into the
several patterns for imple- StopWatchModel.java file,
menting lazy initialization, and well discuss a more
the two most popular being aggressively lazy strategy.
half-lazy and full-lazy. Implementing a full-lazy initialization
To see the eager initialization approach. As shown in Listing 5, the
approach, take a look at Listing 3, in full-lazy initialization approach avoids
which youll see three properties defined instantiating the SimpleStringProperty
in the StopWatchModel.java file from referenced by name when the getName()
the LazyInitEvalExercise project. method is called. It also avoids instanti-
By convention, each of these prop- ation whenever the setName() method is
erties has setter, getter, and property called. It does the latter at the cost of the blog
methods. For example, the lapMillis extra instance variable nameStr, but this
property shown in Listing 3 has meth- is a good approach when the property
ods named setLapMillis(), getLapMillis(), wont typically be used in a binding. Download all listings in this issue as text
and lapMillisProperty(). The implemen- Go ahead and plug in the code from
56
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//rich client /

COMMUNITY
LISTING 6
Listing 5 into the StopWatchModel.java Then, add the following lines to
package javafxpert.lazyiniteval.binding;
file. When youre done, lets move on to StopWatchNode.java:
the next concept, which involves creat-
import java.text.SimpleDateFormat;
ing a custom binding. elapsedTimeStrProperty.bind( import javafx.beans.binding.StringBinding;

JAVA IN ACTION
new TimeStringBinding( import javafx.beans.property.IntegerProperty;
Step 3: Create a Custom Binding stopWatchModel.elapsedMillis
As mentioned previously, the Property() public class TimeStringBinding extends StringBinding {
elapsed time value is formatted ) private SimpleDateFormat timeFormat = new SimpleDateFormat("mm:ss:SSS");
private IntegerProperty millis;
as an integer in Figure 6 but as a );
minutes:seconds:milliseconds string
public TimeStringBinding(IntegerProperty millisArg) {
in Figure 3. This is accomplished by For extra credit, also replace the super.bind(millisArg);
using a custom binding instead of binding for the lapNode textProperty() in millis = millisArg;

JAVA TECH
the default binding provided by the a similar manner so that it appears as }
SimpleIntegerProperty. shown in Figure 3.
To implement a custom binding, Go ahead and run the @Override
protected String computeValue() {
our example defines a class named LazyInitEvalExercise application to verify
int elapsedInt = millis.get();
TimeStringBinding that extends the that the custom bindings cause the
return timeFormat.format(elapsedInt);
StringBinding class, which imple- elapsed time and lap time values to be }
ments the Binding interface shown in formatted as shown in Figure 3. }
Figure 1. You can see the code for the

ABOUT US
TimeStringBinding class in Listing 6. Conclusion
As shown in Listing 6, to imple- JavaFX 2 comes with numerous classes
ment the custom binding we do the and interfaces that provide a powerful
following: properties and bindings framework. You
Define a constructor with the input can optimize the evaluation of bindings
arguments for the binding, calling the and the initialization of properties by
bind() method of the superclass. using the lazy approaches demonstrated
Override the computeValue() method, above. In addition, you can define cus-
returning the desired output value for tom bindings when augmenting the
the binding. default behavior of the bindings in the
To use this custom binding in the JavaFX 2 API as desired. </article>
LazyInitEvalExercise project, com-
ment out the following lines in the
StopWatchNode.java file:

elapsedTimeStrProperty.bind( blog
stopWatchModel.elapsedMillisProp
LEARN MORE
erty() Using JavaFX Properties and Binding
.asString() Michael Heinrichs blog, which includes Download all listings in this issue as text
); entries on JavaFX properties and bindings
57
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//enterprise java /

COMMUNITY
Threading and Concurrency

JAVA IN ACTION
Java EE 6 reflects that centralized management of scarce resources
is becoming more important.

BIO
ADAM BIEN
F rom the beginning, application
servers were designed to pro-
vide shared resources to multiple
Forbidden Threads
Without explaining why, EJB 1.0
prohibited the direct use of
java.lang.Thread constructor, the
SecurityManager is asked for per-
mission. However, most appli-
as described in Stress Testing
Java EE 6 Applications, and
using the results to configure the

JAVA TECH
applications at the same time. threads and synchronization prim- cation servers operate without application server thread pools. A
Scarce resources, such as CPU itives. The EJB 3.1 specification SecurityManager, so applications properly configured thread pool
time, file systems, or RAM, are is even stricter: The enterprise can easily violate the restrictions will reject new requests to prevent
supposed to be shared between bean must not attempt to man- without any consequences. server overloading.
applications. Fair resource shar- age threads. The enterprise bean In addition, the statement Web tier specifications, such
ing, however, requires must not attempt to Allowing the enterprise bean as Java Servlet 3.0, are more
some cooperation THREAD CONTROL start, stop, suspend, to manage threads would liberal regarding thread man-
from the deployed
The uncontrolled or resume a thread, or decrease the containers ability agement. There are no pro-

ABOUT US
applications. to change a threads to properly manage the runtime gramming restrictions related
One of the pro- creation of priority or name. The environment is way too mild. to threading in the Servlet, Java
gramming restrictions threads affects enterprise bean must The uncontrolled creation of API for RESTful Web Services
introduced with the
Enterprise JavaBeans
not only scalability
not attempt to manage
thread groups.
threads affects not only scal-
ability and performance but
(JAX-RS), or JavaServer Faces
(JSF) specifications. Moving
(EJB) 1.0 specification and performance The EJB 3.1 speci- also robustness. Each thread restricted threading code from
was An enterprise but also robustness.
fication explains the consumes memory. Having too the business layer to the presen-
bean is not allowed to reason behind the many threads eventually leads to tation logic or Java Management
start new threads or increased restriction: OutOfMemoryError occurrences Extensions (JMX) beans does not
attempt to terminate These functions are and not only affects the stability solve the problem at all. Its just
the running thread (page 117). reserved for the EJB container. of the application that starts the a hack around the useful restric-
Current restrictions on popular Allowing the enterprise bean to threads, but can crash the entire tions of the EJB specification.
cloud platforms are similar to the manage threads would decrease application server and all the Usually, the Web container and
Java EE programming model. You the containers ability to properly deployed applications. EJB/Contexts and Dependency
could argue that application serv- manage the runtime environ- On the other hand, the appli- Injection (CDI) container are
ers have been cloud-ready since ment (page 599). cation server reuses threads executed in the same Java Virtual blog
the advent of EJB 1.0 in 1998. In practice, application serv- from managed and monitored Machine (JVM). Uncontrolled
Note: Download the source ers can easily prevent direct pools. You can securely prevent thread creation in the Web con-
PHOTOGRAPH BY code for the sample application Thread manipulation by activat- OutOfMemoryError occurrences by tainer can also break the applica-
THOMAS EINBERGER/
GETTY IMAGES described in this article. ing the SecurityManager. In the regularly performing stress tests, tion and crash the server.
58
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//enterprise java /

COMMUNITY
LISTING 1
@Asynchronous Asynchronous methods can also
@Stateless
Before Java EE 6, there was no easy return an instance of java.util.concurrent
public class BatchTask {
way to start threads legally. The Service .Future:
@Inject
Activator pattern (mis)used Java LongTask lt;

JAVA IN ACTION
Message Service (JMS) to asynchro- @Stateless
nously execute synchronous EJB beans. public class LongTask { public void executeInBatch() {
Although Service Activator is concep- @Asynchronous List<Future<String>> results = new ArrayList();
tually a Gang of Four (GoF) Decorator public Future<String> execute(){ //parallelize
for(int i=0;i<10;i++){
pattern, the J2EE realization was overly String result = ...;
results.add(lt.execute());
complicated. You had to encode a // heavy lifting
}
synchronous method call into a JMS return new AsyncResult<String> //gather
message in a proxy implemented as an (result); for (Future<String> resultProxy : results) {

JAVA TECH
EJB bean. The JMS message was sent } try {
with a temporary response queue to a } resultProxy.get(); // use the result, or not
message-driven bean (MDB), which was } catch (Exception ex) { }
}
asynchronously invoked by the JMS run- The first sentence of the Javadoc for
}
time. In the onMessage method, the JMS Future perfectly explains its responsi-
}
message was decoded and the actual EJB bilities: A Future represents the result
method was invoked asynchronously. of an asynchronous computation. A
The MDB waited until the execution Future instance is returned immedi- Download all listings in this issue as text

ABOUT US
of the actual method, converted the ately, and you can use the Future#isDone
return value into a JMS message, and and Future#isCancelled methods to
sent the message back to the proxy. check the progress. You can also use the mal either. The client would effectively will also return immediately.
The implementation of this pattern Future#get method to fetch the return burn CPU cycles. The execution of the method
didnt fit on a single page. The Service value. If the task is not completed, the Future is a useful tool for the paral- BatchTask#executeBatch will take as
Activator pattern can be summarized as invocation of Future#get will block until lelization of multiple task executions in long as the longest LongTask#execute
a local Remote Procedure Call over JMS. the result is computed. batch mode. An additional stateless EJB computation.
With EJB 3.1 and Java EE 6, the whole bean is needed to execute the The code looks sequential, but it isnt.
Service Activator implementation can Batch Processing @Asynchronous methods, cache the In each iteration of the first loop, a task
be replaced with a single annotation. To Using @Asynchronous for void meth- Future in a List and, finally, gather the is passed to a worker pool to be executed
execute a void method asynchronously, ods feels natural. Future, on the other results, as shown in Listing 1. asynchronously. The for-each loop iter-
annotate it with @Asynchronous: hand, does not appear to be particularly The first loop in Listing 1 submits ates over Future instances and occasion-
useful in a standard request-response chunks of work to the application servers ally blocks if the task is not computed
@Stateless scenario. The method annotated with thread pool. The execute() method yet. However, during the wait time for a
public class LongTask { the @Asynchronous annotation immedi- immediately returns a Future instance, computation result, all other tasks are
@Asynchronous ately returns a Future instance, but the which is stored in a java.util.List. In still executed in the background. blog
public void execute(){ Future#get call blocks. the second loop, all Future instances
//heavy lifting Instead of invoking the get method, are asked for their results through the The Right Tool for Fire-and-Forget
} you could use isDone to check the avail- Future#get call. Although the method @Asynchronous is a great tool for the
} ability of the result, but that is not opti- Future#get blocks, in N-1 cases, the call implementation of fire-and-forget use
59
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//enterprise java /

COMMUNITY
LISTING 2 LISTING 3 LISTING 4 LISTING 5
cases. All submitted tasks are queued Asynchronous Servlets
@Stateless
and executed with threads managed by The Java Servlets 3.0 specification intro-
public class PersistentAsynchronous {
the application server. The task queue is duced with Java EE 6 supports asyn-
@Resource
a transient data structurein the event chronous processing. From the HTTP TimerService ts;

JAVA IN ACTION
of an application server crash, all sub- client perspective, there is no difference public void executeAsync(String message){
mitted, but not yet processed, tasks will between an asynchronous and a TimerConfig config = new TimerConfig(message, true);
get lost. traditional Servlet request. In both ts.createSingleActionTimer(1, config);
Because the task queue is transient, cases, the client is blocked until the }
@Timeout
an @Asynchronous method cannot be request is completed.
public void execute(Timer timer){
used as a replacement for the Service An asynchronous request allows the
String message = (String)timer.getInfo();
Activator pattern implemented with Web container to block the browser //do some work
persistent JMS queues. connection without binding a thread. }

JAVA TECH
If a transient thread queue is not an The service method immediately returns, }
option, you can use persistent single- but the AsyncContext instance can still
action timers for asynchronous invo- be used to send messages back to the
cation. In the executeAsync method browser or another HTTP client (for
exposed to the client, you have to regis- example, a JAX-RS client), as shown in
ter a persistent single-action timer first, Listing 3.
as shown in Listing 2. To perform an asynchronous request,
Even parameters can be passed to the Servlet with all filters involved

ABOUT US
the timer as a Serializable instance. in the invocation chain has to be
You have to wrap all parameters in a deployed with the asyncSupported=true
Serializable holder to pass them to the option activated. The method
timer. Because the timer is configured to HttpServletRequest#startAsync() puts the
be persistent, the application server has request into asynchronous mode and
to persist the information callers trans- returns an AsyncContext instance imme- Download all listings in this issue as text
action prior to the timer execution. No diately. The behavior is similar to an
such overhead is needed for the @Asynchronous method returning
@Asynchronous methods, which results the Future instance. An AsyncContext the lock-free CopyOnWriteArrayList message parameter to all listening HTTP
in better performance. instance effectively represents the contexts instance for future noti- clients. The invocation of the onNewEvent
Furthermore, the EJB 3.1 specifi- browser window (or the HTTP client) fications. Each invocation of the method blocks until the message arrives
cation does not define any overload and is used to communicate with the EventBroker#onNewEvent method iterates at the client. It is a classic fire-and-
behavior for @Asynchronous invoca- client after the completion of the service over all AsyncContext instances stored in forget call, so you can easily perform the
tions. The maximum number of method (and doGet, doPost, and so on). the contexts list, passes the String call in the background by annotating the
concurrent requestsand, thus, In Listing 3, the AsyncServlet sends message parameter, commits the method with the @Asynchronous anno-
threadsis unspecified. Most applica- the AsyncContext as a CDI event. request with the AsyncContext#complete tation. In the sample application, the blog
tion servers allow you to configure in a The AsyncContext is received by the method and, finally, removes the String message event is fired in a JAX-RS
proprietary way the thread pool dedi- EventBroker singleton EJB bean shown in AsyncContext from the list. resource (see Listing 5).
cated for the execution of the Listing 4. Each invocation of the onNewEvent Usually, you would not want to expose
@Asynchronous method. The AsyncContext is stored in method effectively distributes the String the HTTP API directly to EJB beans
60
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//enterprise java /

COMMUNITY
LISTING 6 LISTING 7 LISTING 8a LISTING 8b
in the business layer and wrap the manageable network server.
public class BrowserWindow {
AsyncContext in a neutral wrapper. In the JCA connectors work in a connection-
open source project LightFish, the class oriented way, so you will have to
private AsyncContext asyncContext;
BrowserWindow is used to push GlassFish implement at least two additional inter- private final ServletResponse response;

JAVA IN ACTION
monitoring data to the JavaFX 2 client, faces: javax.resource.spi private String channel;
as shown in Listing 6. .ManagedConnection and javax.resource
.spi.ManagedConnectionFactory. public BrowserWindow(AsyncContext asyncContext) {
JCAIf You Want More Fortunately, you can implement both this.asyncContext = asyncContext;
this.response = this.asyncContext.getResponse();
Java EE Connector Architecture (JCA) 1.6 interfaces once and reuse them for mul-
this.response.setContentType("application/xml");
connectors give you the most control tiple JCA connector implementations.
}
over concurrency in a legal, convenient, The class ConnectionFactory (see
and monitorable way. Furthermore, JCA Listing 8a and Listing 8b) exposes the public BrowserWindow(AsyncContext asyncContext,String channel){

JAVA TECH
connectors are managed by the applica- meta-data to the runtime using the this(asyncContext);
tion server, which usually gives you many @ConnectionDefinition annotation and, this.channel = channel;
configuration options. Building a JCA 1.6 together with the @Connector annotation }
connector is not trivial, but it can be on the WorkManagerBoostrap (see
public void send(){
achieved in a few hours. Listing 7), makes the Resource Adapter
try{
The implementation of the Archive (RAR) XML deployment descrip- this.asyncContext.complete();
ResourceAdapter receives the tor obsolete. }catch(Exception e){ }
BootstrapContext in the overridden start The WorkManagerBootstrap is instan- }

ABOUT US
method, which gives you access to the tiated once at connector deployment
WorkManager instance. You can safely time and is effectively a singleton. The public Writer getWriter(){
try {
ignore all other methods defined in the ConnectionFactory needs an instance
return this.asyncContext.getResponse().getWriter();
ResourceAdapter interface (see Listing 7). of the WorkManager stored inside the
} catch (IOException ex) {
You only need to compile the class WorkManagerBootstrap. throw new IllegalStateException("Cannot return writer: " + ex,ex);
shown in Listing 7, put it into a JAR JCA 1.6 SPI comes with a useful }
file, change the .jar extension to interface, javax.resource.spi }
.rar, and deploy the connector. The .ResourceAdapterAssociation, which
application server would create the is used by the container to associ- public void nothingToSay(){
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
WorkManagerBootstrap connector and ate the ResourceAdapter implementa-
httpServletResponse.setStatus(204);
pass the BootstrapContext with which the tion (WorkManagerBootstrap) with the
this.asyncContext.complete();
WorkManager instance can be obtained. ManagedConnectionFactory implementa- }
A WorkManager allows you to execute tion. After casting the ResourceAdapter
javax.resource.spi.work.Work instances to WorkManagerBootstrap, the public String getChannel() {
that extend the Runnable interface. This ConnectionFactory can access the return channel;
solution would work, but your applica- WorkManager instance that is needed for } blog
}
tion would not be able to get a refer- asynchronous execution.
ence to the WorkManager without nasty The ConnectionFactory is just the
hacks. However, this implementation necessary plumbing for managing and Download all listings in this issue as text
would be sufficient to implement a pooling the connections properly. The
61
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//enterprise java /

COMMUNITY
LISTING 9a LISTING 9b LISTING 9c LISTING 10 LISTING 11
method setMaxNumberOf- EVEN BETTER The JCAExecutor implements
public class Connection
ConcurrentRequests exposes the java.util.concurrent
a writable property to the Java EE 7 will
.Executor interface, which will
implements ManagedConnection {

application servers adminis- come with be directly used by the appli- private ConnectionFactory mcf;
even more

JAVA IN ACTION
tration or configuration facili- cation and is created by the private PrintWriter out;
ties. Pooling of already created JCAExecutorFactory, as shown in private JCAExecutor fileConnection;
ManagedConnection instances interesting Listing 11. private ConnectionRequestInfo connectionRequestInfo;
requires implementation of concurrency JCAExecutor with its private List<ConnectionEventListener> listeners;
the matchManagedConnections
method.
features. JCAExecutorFactory are the
actual domain-specific
Connection(PrintWriter out,ConnectionFactory mcf, ConnectionRequestInfo
connectionRequestInfo) {
Usually, a connection is dif- implementation. Most of this.out = out;
ferentiated by the username, the ManagedConnection and this.mcf = mcf;

JAVA TECH
password, or other security cre- ManagedConnectionFactory this.connectionRequestInfo = connectionRequestInfo;
dentials. Here, all thread pools are equal, implementations are business logic this.listeners = new LinkedList<ConnectionEventListener>();
so we just match the connection using agnostic and could be reused for other }
the ConnectionRequestInfo instance. JCA implementations. All classes have
public Object getConnection(Subject subject, ConnectionRequestInfo
Both the ManagedConnection to be packaged into a JAR file that has
connectionRequestInfo)
implementation (Connection) and the .rar extension and deployed to the throws ResourceException {
the ManagedConnectionFactory application server. fileConnection = new JCAExecutor(out,this,mcf, connectionRequestInfo);
(ConnectionFactory) realize connection Java EE applications do not care about return fileConnection;

ABOUT US
management at the logical level and the JCA implementation and are inter- }
are highly reusable. In addition, the ested only in the asynchronous execu-
public void destroy() {
Connection class fires events to notify tion of tasks in a managed environment.
this.fileConnection.destroy();
the application server runtime about the The application-facing API consists of a
}
current state (see Listing 9a, Listing 9b, single interface that returns the Executor
and Listing 9c). to the application, as shown in Listing 12. public void cleanup() {
The Connection instance manages a Now Java EE 6 applications can access }
List of ConnectionEventListeners and fires a managed Executor implementation as
events on close, commit, begin, or roll- easily as in a Java SE environment (see public void associateConnection(Object connection) {
this.fileConnection = (JCAExecutor) connection;
back events. Our connector implemen- Listing 13).
tation is not transactional (but could be
}
implemented as such), so most of the Java EE 7Even Better
events will never fire. With five classes and a simple Maven
As a logical part, the Connection Project Object Modeland without any
also manages its physical counter- XML deployment descriptorsyou get
part. JCAExecutor is the actual meat a flexible thread pool implementation blog
of the connector. Runnable instances that is fully managed by the application
are passed to the execute method to server and could be extended to sup-
be asynchronously executed by the port transactions, security, and prog- Download all listings in this issue as text
WorkManager (see Listing 10). ress monitoring.
62
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//enterprise java /

COMMUNITY
LISTING 12 LISTING 13

import java.io.Serializable;
import java.util.concurrent.Executor;
import javax.resource.Referenceable;

JAVA IN ACTION
public interface WorkExecutorFactory extends Serializable, Referenceable {
Executor newExecutor();
}

YOUR
LOCAL JAVA
USER GROUP

JAVA TECH
NEEDS YOU
Find your JUG here

ABOUT US
Download all listings in this issue as text

Java EE 7 will come with even more not only threaten scalability, but they
interesting concurrency features. JMS also massively affect the robustness
2.0 is going to vastly simplify the pro- of the overall system. The more cloud-
cess of sending and receiving messages. ready your application needs to be, the
EJB 3.2 will likely support additional more important central management
quality-of-service features, such as of scarce resources and, thus, threads
@MaxConcurrency. Java EE 7 will prob- becomes. </article>
ably include a dedicated concurrency
specification.
Threads managed by an application
LEARN MORE blog
are not visible to the application server connectorZ
runtime. It is not possible to throttle the Real World Java EE Night Hacks
concurrency or monitor the applications Dissecting the Business Tier, page 70
behavior. Manually created threads (press.adam-bien.com, 2011)
63
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//mobile and embedded /

COMMUNITY
Wirelessly Back Up Your
Devices Address Book

JAVA IN ACTION
Learn to create a MIDlet to schedule a backup of your address bookand more.
VIKRAM GOYAL

J ava ME applications are notori- other data that your device allows initiate transfers (both The basic code from
BIO
BACKUP PLAN

JAVA TECH
ously hard to back up. In this you to access. on the device and on that previous article
article, I will go through the pro- Note: The source code for the the target platform). You can, in hasnt changed much
cess of creating a MIDlet applica- application described in this I discuss the appli- addition, use this because the process
tion that will allow you to select a article can be downloaded as a cation flow in terms of MIDlet to extend of sending the data is
destination within your Bluetooth NetBeans project here. these logical modules pretty much the same.
network, create a schedule to back next by covering them
backup activities to What is different is
up your address book, perform an The Application Flow one by one. cover other data that that we need to search
on-demand backup, and log (and Figure 1 shows the target applica- your device allows for a Bluetooth con-

ABOUT US
Looking for
view) all of this activity. You can,
in addition, use this MIDlet to
tion in action.
The application flow is divided Destinations
you to access. nection point, find the
OBEX push profile,
extend backup activities to cover among the four options, which I initiated the develop- and then store that
represent logical activities. You ment of this MIDlet information so the
can look for destinations within with the intention of MIDlet can reuse it
the devices Bluetooth environ- using Wi-Fi to detect devices. without any more input from you.
ment, create and edit a sched- However, even though the File To do so, we create a RecordStore
ule to control when the backup Transfer API (JSR 75) supports the and hold this connection point
should be run automatically, discoverability and manipula- (the actual connection URL) in
perform an on-demand backup, tion of folders on remote devices, that database. This RecordStore
and view the log. none of the implementation APIs is called the Backup Store in the
Under normal circumstances, (including Oracles) supports code in Listing 1, and it is initiated
you would create a schedule, set this. I used Bluetooth instead to when the MIDlet starts.
up the destination once, and then discover devices and the services If this destination is not set,
not worry about anything else. In they allowed. any attempt to create a backup
reality, only a signed application I described the Bluetooth dis- will result in a simple message blog
with the proper permissions would covery process and how we can stating that a backup destination
be able to do these things, because use it to send files over the net- is not set.
PHOTOGRAPH BY you would need to grant the appli- work in a previous article, but I will The actual backup destina-
JONATHAN WOOD/
GETTY IMAGES Figure 1 cation permission to read data and cover the main points again here. tion is set after the discovery of
64
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//mobile and embedded /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5
a location, as shown in the EASY ADDS The doSend() method is
// load up the backup dest record store
code in Listing 2 (from the invoked when the MIDlet
BluetoothServices class). I have backed up only wants to send compressed
rs = RecordStore.openRecordStore("Backup Store", false);

Note that we store the the address book. It data to the destination.
// this will get the last record--the last destination for our Bluetooth Device
backupDest = new String(rs.getRecord(rs.getNumRecords()));
would be easy to

JAVA IN ACTION
actual connection URL (There is more informa- if(backupDest == null) throw new RecordStoreNotFoundException("");
so that we dont need to tion about compression
discover the device or the
add a to-do list, a later in this article). The
backupDestSet = true;

services each time the calendar list, or any doSend() method accepts
backup needs to run. You other data that the the destination URL, the
can, of course, look for new
destinations and store
MIDlet may access. filename that we want to
use for this backup, and a
them if preferred. ByteArrayOutputStream that

JAVA TECH
The rest of the code isnt holds the actual data.
much different from my
previous article. BluetoothServices imple- Creating and Editing a Schedule
ments the DiscoveryListener interface, so To keep this part simple, you have the
the deviceDiscovered, servicesDiscovered, option of selecting whether the backup
serviceSearchCompleted, and inquiry- should run automatically on a daily or
Completed methods all have a concrete weekly basis. Adding the ability to spec-
implementation with related UI updates. ify a time is easy enough and is left as an Download all listings in this issue as text

ABOUT US
exercise for you.
Figure 2 shows the UI for setting the
schedule. set to run in a separate thread to avoid RecordStore, the Log Store, as shown in
The top of the screen shows what the any deadlock issues. Listing 4.
current schedule is set to, and below When the MIDlet automatically starts At each call to the log(String message)
that you can select whether to change at the next scheduled run, the start- method, a time stamp is added to the
the schedule. Selecting the Save UI Backup() method is called at the end of message and stored in the log, as shown
option stores this information in another the constructor. This way, the MIDlet is in Listing 5.
RecordStore called the Schedule Store. launched automatically and starts the I have also provided an option to clear
The following code shows how we backup. In the constructor, I also re- the log, because it can get fairly large.
can save the schedule into our Schedule register the next time the MIDlet should Selecting the Clear Log UI option simply
Store and then set up an alarm for self- run based on the nextRun variable picked deletes anything in the Log Store:
invocation of the MIDlet. up from the Schedule Store where it is
This is where I use the registerAlarm() stored, as shown in Listing 3. lrs.closeRecordStore();
method of PushRegistry to set an alarm RecordStore.deleteRecordStore("Log
to restart the MIDlet at the next sched- Viewing the Log Store"); blog
uled run, which is calculated by taking Before we get to the actual backup, lets
into account that there are 86,400,000 look at the View Log UI option. Quite Creating a Backup
milliseconds in a day and 604,800,000 simply, it stores its data at certain crucial The actual creation of the backup hap-
Figure 2 milliseconds in a week. Note that this is points in the MIDlet cycle in yet another pens in two methods: startBackup() and
65
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//mobile and embedded /

COMMUNITY
LISTING 6 LISTING 7

new Thread() {
public void run() {
try {
log("Backup Started At: " + new Date());

JAVA IN ACTION
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LZCOutputStream os = new LZCOutputStream(baos);
// the address book; it's easy to add other lists
ContactList addressbook =
(ContactList)(PIM.getInstance().openPIMList(
PIM.CONTACT_LIST, PIM.READ_ONLY));
createBackup(addressbook, PIM.CONTACT_LIST, os);
btServices.doSend(backupDest, "data.gz", baos);
msgAlert.setString("Done");

JAVA TECH
display.setCurrent(msgAlert, list);
log("Backup Finished At: " + new Date());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}.start();
Figure 3 Figure 4

ABOUT US
createBackup(), although the latter is pri-
Download all listings in this issue as text
vate and called only via the startBackup()
method.
The startBackup() method is called compresses it as it goes along. The paired connection between your device
either automatically when the MIDlet actual looking up of the data is done in and its backup destination, you will get
starts (via your initiation or via the the createBackup() method. the data in a pre-established Bluetooth
PushRegistry alarm) or when you select
Figure 5 The code in Listing 7 goes through Exchange folder. I have tested this pro-
the Do Backup Now UI option. the items in the address book, looks up cess with a live device (Nokia N95) and
As expected, the startBackup() method access (which, admittedly, is limited and a valid data_format for serializing the confirmed that it works perfectly. See
first checks to see whether a backup heavily implementation dependent). items (provided via the PIM API) and Figure 3, Figure 4, and Figure 5, which
destination has been defined. If the des- To make the data transfer faster, I iterates over individual items, while show the activation of the PushRegistry,
tination has not been defined, it alerts used an external library to compress the adding these items to the compres- the destination confirmation, and data
you that the backup cant start. Next, data before it is sent over the Bluetooth sion stream. At the end, the stream is transfer confirmation on the target
it creates a thread to do the backup in channel. This library, called compress- flushed and the data written out. device. </article>
a manner that will not block the main j2me, is extremely small and provides Once the createBackup() method is fin-
thread. See Listing 6. good compression. ished, the startBackup() method uses the blog
In the code in Listing 6, I have backed I start by creating two output streams: doSend() method of the BluetoothServices
LEARN MORE
up only the address book. It would be one for holding the data and the other class we discussed earlier to actually Discovering Devices and Sending Files
easy to add a to-do list, a calendar list, to compress it. The compression stream send the data to the connected device. via Bluetooth in Java ME
or any other data that the MIDlet may takes the first stream as the input and If you have established a trusted and The compress-j2me project
66
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//mobile and embedded /

COMMUNITY
Part 1
Oracle Berkeley DB Java Editions
Java API

JAVA IN ACTION
TED NEWARD Learn how the Java API for Oracle Berkeley DB Java Edition works.
BIO

I n the summer of 2005, while the one we see with the Facebook Using Oracle BEYOND RDBMS level of storage (and

JAVA TECH
at a Microsoft conference, I platform) is nearly impossible. Berkeley DB Java for the most part, the
was asked what I thought of the Not that it cant be done, but Edition is quite
As the NoSQL only reason you would
then-current technical fad, the when a subject requires an entire straightforward, partly movement gained want to do that is to be
object-relational mapping (ORM) book on just that one idea (Joe due to its surface prominence, able to support dupli-
tool. My response, predictably, got
some attention. I said that ORM is
Celkos Trees and Hierarchies in
SQL for Smarties), theres prob-
similarities to the
relational model, but
developers realized cate primary keys), its
useful only to know
the Vietnam of computer science. ably more work there than wed make no mistake that perhaps that such accessibility
At the time, I was definitely really like. attempts to use it as the relational is available and move

ABOUT US
swimming upstream because
everybody knew that the only
As the NoSQL movement
gained prominence, develop-
such are likely to result
in serious failure.
database isnt on to the second API.
Developers who
reasonable place to store data was ers realized that perhaps the the only place remember the C-based
in a relational database, prefer- relational database isnt the only Essentials data needs to go. Berkeley DB APIs
ably a big one. In fact, the bigger, place data needs to go. It might Unlike many database fondly will probably
the betterwho wouldnt want be the last place that data ends APIs, the Java API for find themselves drawn
more RAM, more disk space, up, because thats where we have Oracle Berkeley DB to the base API, but be
faster I/O, the works. the wonderful tools for analysis, Java Edition has two levels. warned: the Oracle Berkeley DB
I argued, in part, that no mat- reporting, and transformation, but The first level, the base API, is a Java Edition manual clearly states
ter how much we try, the different that doesnt mean its the only low-level read/write set of opera- that the file format is not the same
shapes of the datafor exam- kind of storage system available. tions that essentially thinks of format used by the C edition,
ple, our graphs of objects and the For decades, other storage everything in terms of key/value so files arent portable between
databases rectangular tables systems have been quietly han- pairs, where the values are byte each API. Oracle Berkeley DB Java
create mismatches that are very dling data quite nicely, efficiently, arrays that Java developers know Edition files are portable across
hard to eliminate, no matter how and compactly, and one of those, how to create and parse, typically different Java platforms, however.
sophisticated the tooling or librar- Berkeley DB, has been a staple for using either standard Java serial- The second level, called the blog
ies. Its particularly gruesome UNIX-based systems for years. ization or Oracle Berkeley DB Java Direct Persistence Layer (DPL)
to try to shove a hierarchy into a Oracle acquired Berkeley DB a Editions own bind APIs. API, is a more object-centric
table, for example, and trying to number of years ago and has As a general rule, unless you approach to data storage and
PHOTOGRAPH BY
PHIL SALTONSTALL capture a cyclic graph (such as made a Java API available for it. want or need to operate at this more approachable for develop-
67
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//mobile and embedded /

COMMUNITY
LISTING 1
ers who are familiar with ORM tools, Java Edition, opening the database usu-
@Test public void openAndCloseADatabase()
such as the Java Persistence API (JPA). ally consists of telling the API where to
throws DatabaseException
However, its important to note that find the database on disk and whether to
{
Oracle Berkeley DB Java Edition isnt an create the database if it doesnt exist. EnvironmentConfig config = new EnvironmentConfig();

JAVA IN ACTION
ORM, because there arent any actual In the Oracle Berkeley DB Java Edition config.setAllowCreate(true);
tables in the storage files. Instead, the API, doing so consists of creating an Environment dbEnv =
objects go directly into the database, Environment object to represent the new Environment(new File("./someSubdir"), config);
without stopping to be pounded into database environment. This requires
dbEnv.close();
rectangles first. a Java File object, indicating the direc-
}
tory into which the data files will go,
Exploration Testing which must exist ahead of time, plus
When working with a new API, one an EnvironmentConfig object, which

JAVA TECH
approach I like to take is called explora- tells Oracle Berkeley DB Java Edition
tion testing. Essentially, I write unit tests, how it should behave under particular
but not to test the product in question. conditions.
Instead, exploration tests serve several For example, in order to keep the
different purposes: tests clean, the exploration tests
They provide a simple framework in should create and destroy the data-
which to try a number of things. base each time, which means that
They keep the exploration focused on EnvironmentConfig will need to have

ABOUT US
small incremental progress. its allowCreate property set to true, as
They let me make assertions first and shown in Listing 1. Then, as can be
then see if those assertions hold. inferred from Listing 1, closing the envi-
And, most importantly, when a new ronment is done using the close() call.
version of the product comes out, Assuming that someSubdir exists in
running the tests against the new ver- the directory in which the exploration
sion tells me if anything has changed. tests are run, glancing inside reveals
not just one file but several. Of the files
Getting Started there, the critical ones are suffixed Download all listings in this issue as text
A general rule of thumb is that before with .jdb, and they are incrementally
any data can be stored or retrieved from increasing numeric files. The first will
a database, the program has to connect be 00000000.jdb, and this is where EntityStore describe configuration options for the
to (or open) the database. In a tradi- the data will be written as a series of Once the database environment is Environment, the EntityStore is created
tional client-server RDBMS scenario, appending writes one after another. opened, an EntityStore must also be with an EntityStoreConfig. And, just as
opening the database consists of In fact, the Oracle Berkeley DB Java opened on top of Environment in order to EnvironmentConfig has to be told its OK
providing networking information and Edition manual takes care to note that work with the DPL API. (Remember, DPL to create the files if they dont exist, the blog
credentials to (typically) open a TCP/IP backing up these files doesnt require is an abstraction on top of the underly- same is true for EntityStoreConfig, and
socket to the database and authenticate closing the database, as long as the ing key/byte-array-value store.) this is done, again, through the
against it. However, in an embedded backup process copies these files in order, Similar to how the Environment allowCreate property.
database such as Oracle Berkeley DB starting from 0 and working upward. uses an EnvironmentConfig to All of this (and just about everything
68
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//mobile and embedded /

COMMUNITY
LISTING 2 LISTING 3 LISTING 4 LISTING 5
else to do with the DPL API) comes out To store or retrieve an object by its
public class BDBTest
of the com.sleepycat.persist package. primary key, we first have to obtain that
{
For future tests, this code is moved index (a PrimaryIndex<K,V> type, where K
// ...
to an @Before-annotated openDatabase is the PrimaryKey-annotated type and V

JAVA IN ACTION
method and an @After-annotated is the Entity-annotated type that owns it) File dbDir = new File("./data");
closeDatabase method, as shown in from the EntityStore. Environment dbEnv;
Listing 2. Once thats done, we can use the EntityStore dbStore;
@Before public void openDatabase()
Notice that I deliberately chose to PrimaryIndex to put objects into the
{
delete the directory and re-create it each EntityStore and use get to retrieve objects
if (!dbDir.exists())
time just to ensure that no data files are from the EntityStore by the PrimaryKey, as dbDir.mkdir();
lingering after each test. Obviously, for shown in Listing 4.
a production system, the logic would Nary an SQL statement is found, EnvironmentConfig config = new EnvironmentConfig();
config.setAllowCreate(true);

JAVA TECH
be different. which is great, assuming that the exact
dbEnv = new Environment(dbDir, config);
object (or at least its primary key value)
Entities is known to the code doing the lookup StoreConfig storeConfig = new StoreConfig();
Just as with the JPA or any other object- for the object. Sometimes, though, the storeConfig.setAllowCreate(true);
based storage system, when working entire list of objects (such as a list of the dbStore = new EntityStore(dbEnv, "EntityStore", storeConfig);
with the DPL API, we store and retrieve last 10 blog posts) must be looked at, in }
instances of objects. which case an entity iterator is needed, @After public void closeDatabase()
{
Oracle Berkeley DB Java Edition knows which is, again, retrieved from the

ABOUT US
dbStore.close();
that these objects are to be persisted PrimaryIndex<> object (see Listing 5).
because the class is annotated with Take very careful note of the close() call dbEnv.close();
the @Entity annotation. In addition, at on the cursor at finishfailing to do so
least one field on the class must also be will yield an exception from the data- dbDir.delete();
}
annotated with the @PrimaryKey anno- base runtime when the database itself is
}
tation, whose purpose seems obvious, closed. (This is best dropped into a finally
but whose actual use is different than in block, but because these are just explo-
some other ORM systems. ration tests, we can live with it the way it Download all listings in this issue as text
For this example, lets assume the is for now.)
system is a blog engine (see Listing 3). For those cases where the primary
While it might appear that we could key needs to be an artificial key, such as This is equivalent to using glob- Secondary Keys
store a new blog post to the EntityStore in a monotonically increasing numeric ally unique identifiers (GUIDs) as your While this is great, sometimes we need
through some kind of store method sequence, Oracle Berkeley DB Java primary keykeys that are entirely to fetch objects by a criterion other
on the EntityStore, its not that simple. Editions API can generate that key auto- opaque and for which the value is than the primary key. For example, in
The Oracle Berkeley DB Java Edition matically by modifying the @PrimaryKey irrelevant to the actual contents of the a blog system, the blog often needs to
engine insists that we pay closer atten- annotation to use a sequence, for object. Any ability to browse objects show the blog entries for a given day, blog
tion to the indexes defined within the example: and fetch them directly by primary key rather than by their title. This means
store. The most obvious index is the is lost, but nasty business problems are that the database has to pony up the
one that keys off the @PrimaryKey for a private @PrimaryKey(sequence= avoided when using mutable state for objects via a lookup scheme other than
given type. "Sequence_Namespace") int id; primary keys. the primary key.
69
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//mobile and embedded /

COMMUNITY
LISTING 6 LISTING 7
In Oracle Berkeley DB Java Edition, Note that the MANY_TO_ONE is a
@Test public void storeAndRetrieveOneByDate()
this is done by annotating fields with Relationship enumeration, so for this
{
@SecondaryKey and retrieving them to work, that Relationship type must be
BlogPost newPosting =
from the EntityStore by first obtaining imported statically; otherwise, the code new BlogPost("The Vietnam of Computer Science");

JAVA IN ACTION
a SecondaryIndex instance, as shown in needs to read Relationship.MANY_TO_
Listing 6. ONE, as usual. PrimaryIndex<String,BlogPost> primaryIndex =
The SecondaryIndex<> type is tied to dbStore.getPrimaryIndex(String.class, BlogPost.class);
the PrimaryIndex<> type directly. The Wrapping Up . . . for Now primaryIndex.put(newPosting);
first generic parameter is the type of In Part 2, there will be more to explore
SecondaryIndex<Date, String, BlogPost> dateIndex =
the SecondaryKey-annotated field; the on how to store more-complex objects,
dbStore.getSecondaryIndex(primaryIndex, Date.class,
second generic parameter is the type of but this article provided enough to get "postingDate");
the PrimaryKey-annotated field; and the a feel for how Oracle Berkeley DB Java

JAVA TECH
third type is the Entity type itself. The Editions DPL API works. Its essentially EntityCursor<BlogPost> postCursor =
constructor similarly uses the index, the an object persistence store, instead of an dateIndex.entities();
type of the SecondaryKey-annotated field, object-relational persistence store, and for (BlogPost post : postCursor)
{
and the name of that field. this means that there is far less admin-
assertTrue(post.getTitle().contains("Computer Science"));
And if the system needs to fetch istrative work in order to persist objects.
}
a range of objects along that In fact, compared to a relational postCursor.close();
SecondaryIndex, two example values (one schema, theres effectively no work }
from and one to) need to be passed whatsoever: no data definition language,

ABOUT US
in to the entities() call, along with a no server instances to stand up, no
Boolean for each indicating whether that authentication credentials to establish,
example value should be included in the no authorization rules, nothing. Just cre-
returned set (true means inclusive and ate a directory, and away we go!
false means exclusive). See Listing 7. One caveat: As future enhancements
By the way, the SecondaryKey are made to the BlogPost type (perhaps
instances can have a variety of differ- we will add an Author type, describing
ent relationships to their values, as the author of the blog post for those Download all listings in this issue as text
expressed by the relate parameter in blog systems that are multi-tenanted,
the annotation description. The Javadoc such as WordPress), Oracle Berkeley
contains the details, but essentially DB Java Edition will try to just roll with For exploration tests, this isnt a big might require you to write utilities to
its the usual 1:1, 1:n, n:1, or m:n rela- the changes that occur in those types, deal, particularly because Im blowing migrate databases by hand.
tionships seen in every other database thus allowing you to refactor additively away the database entirely after each Finally, I am not advocating that
system on the planet. Because multiple (meaning add-only kinds of refactor- test. But for real databases, this could every relational database instance
blog posts can be posted on a single day, ings, for example, adding fields) with- present a problem between version 1 known to humanity be completely
the postingDate field in the BlogPost type out requiring any change to code. But and version 2. Oracle Berkeley DB Java and utterly destroyed and replaced by blog
is annotated appropriately: changes such as adding the SecondaryKey Edition calls this evolution mutation, Oracle Berkeley DB Java Edition, Apache
annotation to the postingDate field will and while the database can handle CouchDB, or anything else.
private @SecondaryKey(relate= require a more hands-on approach to some of the kinds of mutation that Stay tuned for Part 2, where things will
MANY_TO_ONE) Date postingDate; evolve existing data stores. occur during refactoring, complex cases get a little more complex. </article>
70
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
//fix this /

COMMUNITY
Hint: The bug in the
pool class is not a
concurrency issue.

In the May/June 2012 issue, Angela


Caicedo presented us with a JavaFX code challenge 2 THE CODE

JAVA IN ACTION
around binding. She asked us to consider a code Below is a trimmed code snippet from the pool class. Can you spot the
fragment and determine the output. problem and fix it in place without redesigning the whole program?
The correct answer is #4: you will get an exception private Hashtable connections = new Hashtable();
when you try to call the set method on myBoundInt. private void initializePool(...) ... {
for (int i = 0; i < initialPoolSize; i++)
What is happening? myBoundInt is a bound variable, connections.put(getNewConnection(...), Boolean.FALSE); //
and it is not supposed to be changed directly. You can false=free

JAVA TECH
only change the value of myBoundInt through myInt, }
}
the property myBoundInt is bound to. public Connection getConnection() ... {
// ... find a connection with a FALSE flag ...
This issue s challenge comes from Jason Hunter (top left), connections.put(con, Boolean.TRUE);
author of Java Servlet Programming, 2nd Edition (O Reilly return con;
Media) and deputy CTO at MarkLogic, and Boris Shukhat, }
public void returnConnection(Connection returned) {
applications programming manager, vice president, Bank of

ABOUT US
connections.put(returned, Boolean.FALSE);
America Merrill Lynch. }

1 THE PROBLEM 3 WHAT S THE FIX?


1) I nstead of Connection, use a PooledConnection.
The ConnectionPool.java example from Chapter 9 of
Java Servlet Programming has a subtle bug. The pool code 2) Instead of Hashtable, use another implementation of
worked fine for many years, but a recent upgrade to a the Map interface.
JDBC driver broke it. 3) Extend the problematic Connection implementation,
overriding some methods.
4) Create an implementation of Connection wrapping the
problematic Connection.
blog

GOT THE ANSWER?


ART BY I-HUA CHEN
Look for the answer in the next issue. Or submit your own code challenge!
71
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012
COMMUNITY
EDITORIAL
Editor in Chief
Justin Kestelyn
Senior Managing Editor
Caroline Kvitka
PUBLISHING
Publisher
Jeff Spicer
Production Director and Java Skills
#1 Priority
Associate Publisher
Community Editors Jennifer Hamilton+1.650.506.3794

JAVA IN ACTION
Cassandra Clark, Sonya Barry, Senior Manager, Audience Development
Yolande Poirier and Operations
Java in Action Editor Karin Kinnear+1.650.506.1985
Michelle Kovac ADVERTISING SALES
Technology Editors Associate Publisher
Janice Heiss, Tori Wieldt Kyle Walkenhorst+1.323.340.8585

Of Hiring Managers
Contributing Writer Northwest and Central U.S.
Kevin Farnham Tom Cometa+1.510.339.2403
Contributing Editors Southwest U.S. and LAD
Blair Campbell, Claire Breen, Karen Perkins Shaun Mehr+1.949.923.1660
Northeast U.S. and EMEA/APAC

JAVA TECH
DESIGN Mark Makinney+1.805.709.4745
Senior Creative Director
Francisco G Delgadillo Recruitment Advertising
Tim Matteson +1 310-836-4064
Senior Design Director
Suemi Lam Mailing-List Rentals
Contact your sales representative.
Design Director
Richard Merchn
Contributing Designers
RESOURCES
Oracle Products
Get Certified with Oracle University
Jaime Ferrand, Nicholas Pavkovic +1.800.367.8674 (U.S./Canada)
Production Designers Oracle Services Prepare with Java experts

ABOUT US
Sheila Brennan, Kathy Cygnarowicz +1.888.283.0591 (U.S.)
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
java@halldata.com 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 2012, 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
Click to Register
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 Oracles
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.

Digital Publishing by Texterity Source: from Dice.coms Dice Report; January 2012: The Top Spots

Copyright 2012, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates.

ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// JULY/AUGUST 2012

You might also like