McQueeney.com
 

Tom's Blog

Josh Bloch's Java puzzlers tonight in D.C.
Published by Tom | March 27, 2007 10:57 AM EST |
I just heard that Joshua Bloch from Google will be in downtown D.C. tonight presenting "Java Puzzlers' Greatest Hits." If you haven't seen his presentation at a conference or JUG meeting, I highly recommend attending. Bloch throws Java code snippets or questions related to Java up on the wall, and audience members puzzle-out the answers. I learned things about Java that surprised me when I first heard his talk in 2004. The simple snippets of Java code in his questions often don't do precisely what you'd think -- because they won't compile, because of primitive integer overflow, because the code stumbles into a collections corner case, or other Java language subtlety.

Since his 2004 talk, Bloch has written a book on the puzzlers, Java Puzzlers: Traps, Pitfalls, and Corner Cases (Addison-Wesley, 2005) with Neal Gafter -- and also left Sun Microsystems to join Google as chief Java architect.

Here are the details of Bloch's presentation, hosted by Google. RSVP to pittsburgh@google.com.

When: 6:00pm
Date: Today, Tuesday, March 27
Where:
The Renaissance Mayflower Hotel, Senate Room
1127 Connecticut Ave. NW
Washington, DC 20036
Metrorail: Farragut North or Farragut West (head north on Connecticut)
Hotel phone: 202-347-3000


20070327 Tuesday March 27, 2007 Permalink
Eclipse gave a surprising left jab while unboxing
Published by Tom | February 27, 2007 11:30 PM EST |
I'm working on a project for a client to integrate an existing web-based mortgage application to work with a large mortgage-loan consolidator. The existing application has a large code base originally targeted for Java 1.3. We needed to create an integration API and wanted to take advantage of some of the concurrency classes introduced in Java 1.5. The client gave approval to use 1.5 for the new code.

Upgrading went smoothly. We had to rename an existing package that included the new enum keyword, but the 1.3 code easily upgraded to 1.5. Being able to use 1.5 was nice because I like the generics support, the simplified "for-each" syntax to iterate over collections, and the simplified concurrent package. Many of the new concurrency features also are available for earlier versions of Java in the backport-util-concurrent library. I like Eclipse's support for 1.5, such as typing "foreach[Ctrl-SPACE]" and having Eclipse make a pretty good guess at filling in the simplified for-each loop code, including the collection reference to iterate over, and picking a good name for the temporary iterator variable.

For example, if you start a method:
    public CreditReport getTriMergeForBorrower(
        Borrower borrower, Set creditReports
    ) {
and you want to loop over the creditReports to search for the correct one for this borrower, you can type:
        foreach[Ctrl-SPACE]
and Eclipse will replace that with:
    for (CreditReport report : creditReports) {

    }
Eclipse looks "up" in the code to find the nearest iterable, fills in the correct type for the iteration temporary variable, and gives the temporary variable a reasonable name. Pretty nice. But as the title of this entry implies, I got an unexpected jab from Eclipse, or more accurately, my reliance on it.

Eclipse is aware of another "new" feature in 1.5: autoboxing and unboxing. Autoboxing is the term for the Java compiler allowing you to write code that treats primitives as their equivalent object types (an int treated as if it were a java.lang.Integer, for example). Auto-unboxing is the opposite: using an object when the expression calls for a primitive. If you haven't been able to use Java 1.5 on a project, here's a short introduction.

With autoboxing, you can write code like this (from the above-reference Sun website):
    public static void main(String[] args) {
        Map m = new TreeMap();
        for (String word : args) {
            Integer freq = m.get(word);
            m.put(word, (freq == null ? 1 : freq + 1));
        }
        System.out.println(m);
    }
Notice how it appears you can pass an int as the parameter to be inserted into the TreeMap. Even though you really can't put a primitive into a collection like a map, the compiler (not the Java runtime) corrects this "incorrect" coding by inserting hidden code to create an Integer object to wrap the primitive int value. Autoboxing makes the code look a little cleaner: Let the compiler do the work rather than the programmer.

I've known you could write autoboxing code like the above for a couple of years. In August, 2004, two months before Java 1.5's general release, I attended a talk by Joshua Bloch and Neal Gafter at the Denver Java Users Group, introducing the new features in Java 1.5 (Tiger). But what I hadn't considered was that you sometimes could write auto-unboxing code without realizing it. It happened to me with code like:
    if (creditReport != null && creditReport.isTriMerge()) {
       // do some processing
    }
When testing the code, it threw a NullPointerException. When I saw the stack trace, I said Huh? The creditReport reference obviously isn't null when invoking isTriMerge, so where did the NPE come from? A moment later, it hit me. The isTriMerge method must be returning a Boolean, not a boolean as I had assumed when I looked at the business object's API using Eclipse's Ctrl-SPACE to show options. I let Eclipse fill in the isTriMerge method name when I typed the if statement. Eclipse didn't complain about the syntax, so my natural assumption was a method named "isXXX" would return a boolean.

Instead, the CreditReport business object uses object wrappers for all its primitive-value fields, so when the object is persisted in the database, it can use NULL values to indicate "unspecified." The getters all return objects.

When writing code that takes advantage of unboxing, you can end up creating seemingly odd statements like:
    if (creditReport.isTriMerge() != null &&
        creditReport.isTriMerge()
    ) {
        // Do something
    }
where you check a value for null and whether the value is true. It looks unusual, compared to the pre-Java 1.5 version:
    if (creditReport.isTriMerge() != null &&
        creditReport.isTriMerge().booleanValue
    ) {
        ....
which is what the compiler is actually inserting into the .class file's bytecode.

Unexpected NullPointerExceptions occur when you don't realize that your "primitive" value is really an object being dereferenced inside hidden code. I found this big discussion of automatic unboxing on TheServerSide from three years ago, debating whether unboxing is a good thing.

So, live and learn. I don't see autoboxing/unboxing as bad. Programmers just need to be cognizant of whether a variable holds a reference to a primitive object wrapper rather than a true primitive value, and whether a method returns an object rather than a primitive. And if you want to be cautious, you can ask Eclipse to warn you about possible unboxing problems. Eclipse (I'm using 3.2) has a Java code setting: Window | Preferences | Java | Compiler | Errors/Warnings | Potential programming problems | Boxing and unboxing conversions. You can tell Eclipse to flag boxing/unboxing in the code as a warning or error. That way, you're less likely to receive an unexpected jab from hidden unboxing code. Eclipse's default is to ignore boxing and unboxing in the code as long as it's legal syntax. (I'm sure IDEA and NetBeans can do the same thing. If you're an IDEA or NetBeans user and want to post those IDE equivalents in a comment, please do.)


20070227 Tuesday February 27, 2007 Permalink Comments [4]
Celebrating the first American in orbit 45 years ago
Published by Tom | February 25, 2007 11:10 PM EST |
Last week, NASA and the United States celebrated 45 years of Americans in orbit. On Feb. 20, 1962, an Atlas missile launched astronaut John H. Glenn Jr. into a cloudless sky on a trajectory that allowed his tiny Friendship 7 spacecraft to orbit the earth three times. The successful mission let the U.S. hold its head a little higher after the Soviets beat the United States into space yet again (i.e. Sputnik) when it launched Yuri Gagarin into orbit aboard Vostok 1 on April 12 the previous year. The flight also helped the world believe the United States might actually achieve what President Kennedy had proposed less than a year earlier: to land a man on the moon and return him safely to earth.

NASA photo of John Glenn leaving crew quarters prior to launch
NASA
John Glenn, in his pressure suit,
leaving crew quarters.
Prior to the Friendship 7 mission, the U.S. had launched two men only into short sub-orbital flights. The U.S.'s space program seemed years behind the Soviet's. During the weeks leading up to Glenn's space flight, the world witnessed the U.S. delaying the launch 10 times because of equipment problems and uncooperative weather.

NASA's web pages celebrating the 45th anniversary includes an interview with the astronaut-turned-senator, John Glenn, interviews with fellow Mercury astronauts Scott Carpenter and Walter Schirra, and a 360-degree tour of the Friendship 7 capsule, allowing you to zoom in on panel switches and indicators to know just what they say. The presentation allows you to see more capsule details than you would straining to peer inside the capsule in person at the National Air and Space Museum in Washington. (But by no means do you want to miss seeing the capsule in the museum's lobby when you visit D.C. You also can see Glenn's Mercury space suit, although make sure you read the label next to the suit to avoid leaving with the impression that John Glenn stood about 4-foot-10.)

Friendship 7 leaves the launch pad atop an Atlas-D rocket
Friendship 7 leaves the
launch pad atop an
Atlas rocket
NASA's Johnson Space Center also archives many press photos of the Friendship 7 mission. Well worth viewing if you're a space buff. A complete recording of the flight also is available from the Kennedy Space Center as a series of Real Audio files.

Listening to the audio of the entire flight is a good way to live through the event, rather than listening to edited versions of the flight. As an example, for a project I worked on 12 years ago commemorating the 25th anniversary of the Apollo 11 moon landing, I listened to some of the unedited NASA recordings. I remember thinking how slow everything occurred, from the descent of the lunar module to the hours that passed between touchdown ("Houston, Tranquility Base here, the Eagle has landed") and Neil Armstrong actually stepping out onto the surface ("That's one small step...") Whenever the moon landing is shown on television today, you'd think the landing took a couple of minutes and that the astronauts popped the hatch shortly after landing. Listening to the full recording of the 4 hour, 55 minute Friendship 7 flight gives a reminder to the many details that actually occur during a space flight.

If you'd like to hear highlights of the Friendship 7 flight, here are some edited audio files from my collection.
Launch (56 seconds)
Hitting zero G: "Zero-G and I feel fine" (55 secs.)
Firing retro rockets (21 secs.)
Main parachute deploy (40 secs.)

These recorded highlights are fun because you can hear Glenn describing the power of the retro rockets being fired while he was passing over California on his way toward his splashdown target in the Atlantic Ocean. Glenn radios, "Retros are firing. Are they ever. It feels like I'm going back toward Hawaii." You also can hear the excitement in Glenn's voice when he sees his main parachute deploy, which was probably the last major thing that could have gone wrong before splashdown. You hear Glenn's relief when he says "beautiful chute."

Photo of earth taken by astronaut John H. Glenn Jr. during his spaceflight
NASA
Photo of earth Glenn took during his space flight
Glenn had reason to be nervous during re-entry. Ground controllers had received telemetry indicating that the heat shield and landing airbag assembly (in case he needed to make a hard landing on the ground) might have prematurely detached from the capsule. If true, the only thing keeping the heat shield in place were straps attaching the retro-rocket assembly to the space craft. As a safety measure, flight controllers asked Glenn to keep the retro-rockets attached to the space capsule during re-entry. Normally, the rockets are jettisoned after firing. During re-entry, Glenn heard thumps and saw pieces of the retro rockets burning away from his craft.

You also hear in the recordings why NASA later suggested sending a poet into space in order to describe the experience (and thus gain more public support, and funding). It seems Glenn has one word for all the wonders he sees. Sunrises and sunsets? Beautiful. The site of the secondary engine falling away from his craft? Beautiful. Parachute? Beautiful. NASA was hoping the astronauts could provide more vivid descriptions to bring the experience to life.

If you start reading through some of the NASA links and want to learn more about Mercury, I recommend We Seven, a book from 1962 by the Mercury astronauts themselves, describing the program. I remember reading that book when I was about 11, getting me hooked on the excitement of science and exploration. The Wikipedia entry also is good.


20070225 Sunday February 25, 2007 Permalink
Ajax Architecture with Stuart Halloway
Published by Tom | November 04, 2006 07:51 AM EST |
When should you use Ajax? Whenever you want to create a rich client application with the universal reach of the Internet. Stuart Halloway, speaking Friday afternoon at this fall's Northern Virginia Software Symposium, predicts Ajax will be part of nearly all web applications within the next year. Stuart's first session of the day focused on the architectural issues involving Ajax, from technical features to selling Ajax to management. In 90 minutes he discussed:
  • the reasons to use Ajax
  • how to introduce Ajax at your company
  • the resistance you'll encounter when you do
  • the tools and libraries to use in Ajax development
  • the architectural decisions you'll need to make
  • how Ajax isn't a panacea for all applications
Stuart demonstrated Ajax in action by showing how to build several incarnations of a web form that, once you input a U.S. Zip code, the address's city and state fields fill in automatically from an asynchronous JavaScript server call. Low-tech stuff compared to Google Maps, but simple enough to demonstrate several ways to get the job done.

The interest in Ajax has been increasing over the last couple of years not because of a breakthrough in technology, Stuart said, but because of a breakthrough in how we look at using asynchronous JavaScript to make web forms more dynamic. Instead of having web user-interface developers deal with the vagaries of the different browser versions, different implementations of JavaScript, different implementations of Cascading Style Sheets, and different implementations of the web page document object model, they learned in February 2005 from
Jesse James Garrett photo
Jesse James Garrett
Jesse James Garrett to hide browser differences behind an adaptive interface provided by a library like Prototype or Dojo. Garrett coined the term Ajax in his seminal paper, "Ajax: A New Approach to Web Applications." Of course, it also helps, Stuart added, that the functionality provided by Internet Explorer and Firefox have converged over the years.

The reason to use Ajax in your web applications is to create a better experience for your users. Ajax allows your web page to communicate to the server in order to update the page "behind the user's back," making the application more responsive to the user's actions without having to reload the page.

The best way to introduce Ajax at your company, he said, is in non-core web applications. Depending on your company's culture, Stuart said, you can sell Ajax either as proven technology -- XML, HTTP requests, and JavaScript -- or by saying "Ajax is the revolution and we're all on board." When introducing Ajax, he said, stay "degradable." That is, ensure your web application still works if the user turns off JavaScript or uses a browser that doesn't support it. The fewer negative issues you create, the more the benefits will shine through and convince others to introduce Ajax into more web applications. If you want to be conservative, he said, wait until the web MVC frameworks, like JavaServer Faces, provide better support for Ajax in their page widgets.

Stuart mentioned several open source development tools and JavaScript libraries to use in your Ajax applications:
  • Firefox
    Consider the Firefox browser (with its extensions that follow) your development platform and Internet Explorer as your deployment platform, Stuart said.
  • JavaScript Shell
    a Firefox bookmarklet that allows you to dynamically run JavaScript statements against your current page in a debugging window. This tool is useful, Stuart said, "for poking around the page to figure out what's broken."
  • FireBug
    a Firefox add-on with debugging features to monitor your page's JavaScript, CSS, and HTML. One feature allows you to spy on all HTTP traffic JavaScript functions send to the server.
  • Web Developer
    a Firefox add-on toolbar that allows you to disable JavaScript, cookies, view and modify a page's CSS, view a page's generated source rather than the HTML originally loaded, and a host of other useful development tools.
  • Tamper Data
    a Firefox add-on that logs all web navigation. It not only allows you to see what requests and responses are traveling between the Ajax components and the server, but it allows you to modify them or completely stop the request and see how the application reacts.
Ajax Libraries

Stuart mentioned several Ajax libraries. Since JavaScript libraries generally don't trample on each other, he said, you can often use more than one in a web application.
  • Prototype
    A survey at an Ajaxian conference showed that more than half of the Ajax developers were using Prototype, Stuart said. Most of the rest were using Scriptaculous (next). Prototype allows you to register multiple event handlers to events (Event.observe()). You can register events outside of the HTML widget to allow you to separate concerns: your HTML page designer doesn't have to worry about coding the JavaScript events. Prototype also provides the Ajax.Request function that works as a factory to return the appropriate function that works with the user's browser version.
  • Scriptaculous
    A library built on Prototype to provide page effects (highlight, fade), drag and drop, auto-complete and other features.
  • Dojo
    This is a heavy-weight "kitchen sink" library, Stuart said, that provides almost everything you need for an Ajax application.
  • Google Web Toolkit
    This toolkit allows Java developers to build front-end components in Java. The toolkit converts the Java code to JavaScript and HTML.
  • Direct Web Remoting
    Stuart said DWR is No. 3 in popularity, behind Prototype and Scriptaculous. It's Java RMI like. You write JavaScript stubs that run in the browser and make RMI calls to the server. It assumes you have Java running on the server side.
Introducing Ajax into an application raises two key architectural questions, Stuart said. These are the questions to think about early and thoroughly because changing the answers later could undermine previous development work.
  1. What to send on the wire?
    When JavaScript calls to the server for updated information, does the server send back HTML, XML, JavaScript, or JSON? HTML is view centric, JavaScript is code-centric, and XML and JSON are model-centric. (See also this blog for a discussion.)

    Stuart said he believes 95% of all Ajax traffic soon will be HTML. It's developer-efficient (no parsing and XML creation) and the snippet of HTML can simply be rendered on the page. JSON will dominate applications that focus on data exchange because it is easier to parse than XML. XML will be the loser. Sending back JavaScript allows you to send back code that the browser would evaluate.

  2. What library to use?
    Choose a library that supports the features you need. The library should hide the browser differences in the XMLHttpRequest. Prototype does this and builds upon JavaScript to make it more like a regular programming language.

    Use Scriptaculous if you need to adds page effects and you'd like to use its widgets.

    Dojo is the library beloved by Java programmers, Stuart said. It's bigger than all the other libraries, but it does more. Its API provides fixes for Back-button issues, client-side data storage, and other features.

    Stuart dislikes Google Web Toolkit. "I think it's architecturally wrong," he said, but I think I zoned out when he described the reasons for his dislike.

Although Ajax is useful, it won't be a panacea for all applications, Stuart said. Learning to design with Ajax correctly will involve some of the same growing pains the development community learned in creating n-tier applications. Stuart likened the future growing pains in the Ajax world to the pains Java programmers suffered in implementing n-tier web applications using EJB. "We're going to make a ton of mistakes" implementing Ajax applications, he said. "Asynchronous is hard. Asynchronous is as hard as threads, except you don't have an API in front of you reminding you how hard it is."
20061104 Saturday November 04, 2006 Permalink
Filling in my No Fluff dance card
Published by Tom | November 03, 2006 08:30 AM EST |
Today begins the fall session of the Northern Virginia Software Symposium put on by No Fluff Just Stuff (Jay Zimmerman and crew). That means I have to decide which one of the six concurrent sessions to attend in each time slot. That means I have to decide which of five sessions to miss during each time period.

Today has three time slots in the afternoon, followed by an after-dinner keynote by pragprog co-founder Andy Hunt. For the 1:15 p.m. session, I'd like to attend Stuart Halloway's "Ajax Architecture" session, Brian Goetz's "Java Performance Myths" session, and Venkat Subramaniam's "Open Source Tools for Agile Development" session. I'm not a web UI designer, but knowing the browser's asynchronous JavaScript abilities would help on a current project. We want to add dynamic page updates to an existing web application. The design of the server code I'm working on will be affected by what services the client needs. Brian Goetz's session promises to show how common Java idioms we use, thinking it helps the Java compiler optimize our code, actually make it harder for the JIT compiler to figure out how to optimize. Venkat Subramaniam will recommend open source tools he finds most useful to develop code and improve its quality. The open source world changes so fast, it would be good to get these tips from the good doctor.

See how hard Jay makes it to decide which session to attend? I'm leaning toward Stuart's Ajax session just because it's the area I know the least about. I'd like to know what cool features Ajax libraries Prototype and Scriptaculous provide.

Later in the afternoon, Venkat has sessions on test-driven design for Spring applications and working with rules engines. But these sessions conflict with sessions on how Acegi supports JavaScript for better user authentication interaction, and a session on Jini (the technology whose coolness keeps it alive despite being almost wholly ignored for years). Decisions, decisions.

I plan to blog more this weekend on the sessions I attend and what I learn.


20061103 Friday November 03, 2006 Permalink