Thứ Bảy, 24 tháng 3, 2012

Software Development Posts of Interest - March 2012

This post references some of the recent blog posts and articles that have interested me. Topics include Java-specific topics such as Java EE, JavaFX, Scala, and Gradle as well as more general software development topics such as software patents and open source.

Why Software Patents are Evil

Simon Phipps summarizes in Why software patents are evil why patents in software may not make sense:

Patents may work in other industries, where the cost of innovation is so high that a temporary, state-sanctioned monopoly provides just enough time to gain a return on the investment. But that investment-return ratio has a completely different value for software. It turns out that software patents have little bearing on encouraging innovation. ... Software patents are ... bad news for most innovators in the software industry.

Phipps also looks at the relationship between software patents and open source software. He writes, "The problem is that open source software is defenseless against the anticompetitive abuse of patents."

Java EE 6 Versus Spring Framework

In the post Why is Java EE 6 better than Spring? Arun Gupta discusses why he believes developers should use Java EE 6 rather than the Spring Framework. Gupta begins the post by referencing several similar blog posts including Java EE wins over Spring and Why I will use Java EE (JEE, and not J2EE) instead of Spring in new Enterprise Java Projects in 2012.

Some of the feedback comments on this post are interesting because they demonstrate the differences of opinions between Java EE evangelists and Spring Framework evangelists (with comments from employees of both Oracle and SpringSource/VMWare among them). It is interesting to see the role reversal in this situation. Evangelists of the Spring Framework (even before it was so named) helped convince the Java enterprise development community of the problems with early J2EE, but now it seems the tables have turned and similar evangelism is advertising the "legacy" nature of Spring Framework as compared to modern Java EE.

Java EE 6 vs Spring - let's get ready to rumble provides another look at this post.

Oracle's Long-Term Intentions for Java

Paul Krill's Oracle lays out long-range Java intentions summarizes the "Oracle slide presentation entitled 'To Java SE 8 and Beyond!' posted on the QCon conference website." Based on Krill's summary, this presentation sounds very similar to the Oracle OpenWorld 2011 presentation From Java SE, 2012, to Java 12: Java SE Roadmap.

Reducing Memory Usage and Garbage Collections with -XX:+UseCompressedOops

Stuart Leneghan's post Reducing Java Memory Usage and Garbage Collections with the UseCompressedOops VM Option looks at the author's observation of the -XX:+UseCompressedOops HotSpot-specific JVM option "[reducing] the memory usage of the application by 14% and the number of garbage collections by 24%."

More on Java Tuning

Speaking of Java performance and memory tuning, Rupesh Ramachandran's post Java Tuning in a Nutshell - Part 1 provides a "JVM tuning cheat sheet" and categorizes JVM options into four categories: garbage collection, heap tuning, logging, and other performance.

The IBM DeveloperWorks article From Java code to Java heap is fairly comprehensive, providing background details on JVM memory handling and a focus on the impact of different Java collections on memory. This article also references the HotSpot option -XX:+UseCompressedOops as well as the similar IBM JVM option -Xcompressedrefs.

Understanding Garbage Collection is another recently-posted resource. This post is "the first of a series of 'Become a Java GC Expert' articles" and its focus is on introducing garbage collection in Java. The same site also hosts the blog post How to Analyze Java Thread Dumps. Figure Out Why Java is Eating CPU provides an interesting tip.

Scala

There continues to be a profusion of Scala posts. Recent posts include How Scala Can Improve Your Life, Is Scala making the right steps forward?, Scala creator Martin Odersky fends off critics of Scala's roadmap, Free online books for learning Scala, and Scala: Sink or Swim? Part 1. I have also seen new references to Twitter's Effective Scala.

Unit Testing

Neil Buesing's post How to Mock Final Classes in Unit Tests examines the problem that "both Mockito and EasyMock cannot mock classes (or methods) that are final." The feedback comments are also informative and discuss other available solutions to this issue: PowerMock), Groovy-based gMock, and JMockit.

Improved Java Stack Trace Presentation

Tomasz Nurkiewicz has posted two blog posts on how to improve Java stack trace experience using the Logback Project. Filtering irrelevant stack trace lines in logs demonstrates his "proof-of-concept" for filtering out selected stack trace frames using Logback and references the StackOverflow thread Cleaning noise out of Java stack traces. An older post, Logging exceptions root cause first, discusses a feature he contributed to Logback for displaying exceptions with root cause first rather than last.

A Peek at NetBeans 7.2

Geertjan Wielenga's NetBeans Java Hints: Quick & Dirty Guide provides a peek at a capability coming in NetBeans 7.2 for creating NetBeans hints.

Gradle

Last milestone for Gradle as it prepares for first major version cites the Gradle roadmap and states that the current version of Gradle ("1.0-milestone-9, released on 13th March 2012") "will be the final one" before Gradle goes into release candidate.

GroovyFX and JavaFX

Gradle is not the only product in the Groovy ecosystem with recent version advancement news. Dean Iverson has announced the GroovyFX First Official Release. He also shows how to use Grape to "grab" GroovyFX similar to the approach shown in my post Easy Groovy Logger Injection and Log Guarding.

Other interesting recent posts related to JavaFX include Example CSS Stylying in JavaFX, New in JavaFX 2.1: ComboBox, and Packaging JavaFX Applications as Native Installers.

Groovy and DevOps

In the post Groovy, A Reasonable JVM Language for DevOps, Geoffrey Papilion writes that Groovy provides the "JVM glue" he sought for "a simple JVM language that allows me to use any native object." After demonstrating use of Groovy for a "quick script to get data from JMX into ganglia fromSsolr," he concludes

So, if you're working in a Java with a bunch of Java apps, think about giving Groovy a chance for writing some of your monitoring tests, and metric collectors. It is a simpler language than Java to put together those little applications that can tell you how your system is performing, and well within the reach of your average DevOps engineer.
DNS for Software Developers

Doug Rathbone's post DevOps DNS for Developers – Now There’s No Excuse Not To Know is intended to help software developers become more familiar with the basics of DNS. This does seem like the sort of article one would except to be associated with the DevOps movement.

The Big Three JVM Languages

The Big Three – Scala, Clojure and Groovy is a blog post with observations about Groovy, Scala, and Clojure seeming to be the most popular JVM languages among Java developers based on two polls (Which alternate JVM language do you prefer? and Which JVM Language Is On Top?). Charles Oliver Nutter has added a feedback comment regarding JRuby being a more popular JVM language when you consider Ruby developers.

Java 7 WatchService

The post What’s New in Java 7: WatchService describes java.nio.file.WatchService and calls the related functionality "one of the more interesting ... new features in Java 7." This is a fairly concise post that quickly introduces the functionality and includes sample code.

Opinions on Rails, Hibernate, Google, JSON's License Agreement, and the Spanish Theory of Management

I started this post with reference to an opinion-oriented post on open source and patents. It seems symmetrically pleasing to close this post with references to other opinion-oriented pieces. Tyler Menezes discusses technical and cultural reasons he won't use Ruby on Rails in the simply titled post I will not learn Rails. James Whittaker provides a articulate and insightful post Why I left Google.

Rob Gordon is "not impressed" with Hibernate 4.1 ease of use. The Dodgy Coder blog ("Never trust a programmer in a suit") includes a post on the "Spanish Theory" of project management.

Brian Fox points out that JSON's license agreement states "The Software shall be used for Good, not Evil." Fox further points out that "compliance is impossible" and that "this isn't even open source." He asserts that "this additional clause adds an unnecessary complication" and I tend to agree. The folks in suits are not comfortable with objective statements in the license agreements.

Conclusion

I have summarized and linked to Java-specific and general software development posts of interest in this blog post. The software development industry continues to be ever-changing and full of news.

Thứ Hai, 19 tháng 3, 2012

ToString: Hexadecimal Representation of Identity Hash Codes

I have blogged before on the handy Apache Commons ToStringBuilder and I was recently asked what the seemingly cryptic text appearing in the generated String output constitutes. The colleague asking the question correctly surmised that what he was looking at was a hash code, but it did not match his instance's hash code. I explained that ToStringBuilder adds the identity hash code in hexadecimal format to its output. In this post, I look in more depth at ToStringBuilder's use of the identity hash code presented in hexadecimal format. Even those not using ToStringBuilder might find this information useful as Java's standard Object.toString() also uses a hexadecimal representation of what is effectively its identity hash code.

I'll begin with a very simple Java example using ToStringBuilder. This example uses three Java classes (Person.java, Employee.java, and Main.java) that are shown next.

Person.java

package dustin.examples;

import org.apache.commons.lang.builder.ToStringBuilder;

/**
* A simple representation of a Person intended only to demonstrate Apache
* Commons ToStringBuilder.
*
* @author Dustin
*/
public class Person
{
/** Person's last name (surname). */
protected final String lastName;

/** Person's first name. */
protected final String firstName;

/**
* Parameterized constructor for obtaining an instance of Person.
*
* @param newLastName Last name of new Person instance.
* @param newFirstName First name of new Person instance.
*/
public Person(final String newLastName, final String newFirstName)
{
this.lastName = newLastName;
this.firstName = newFirstName;
}

/**
* Provide String representation of this Person instance.
* @return My String representation.
*/
@Override
public String toString()
{
final ToStringBuilder builder = new ToStringBuilder(this);
builder.append("First Name", this.firstName);
builder.append("Last Name", this.lastName);
return builder.toString();
}
}
Employee.java

package dustin.examples;

import java.util.Objects;
import org.apache.commons.lang.builder.ToStringBuilder;

/**
* Simple class intended to demonstrate ToStringBuilder.
*
* @author Dustin
*/
public class Employee extends Person
{
/** Employee ID. */
private final String employeeId;

/**
* Parameterized constructor for obtaining an instance of Employee.
*
* @param newLastName Last name of the employee.
* @param newFirstName First name of the employee.
* @param newId Employee's employee ID.
*/
public Employee(
final String newLastName, final String newFirstName, final String newId)
{
super(newLastName, newFirstName);
this.employeeId = newId;
}

/**
* Provide String representation of me.
*
* @return My String representation.
*/
@Override
public String toString()
{
final ToStringBuilder builder = new ToStringBuilder(this);
builder.appendSuper(super.toString());
builder.append("Employee ID", this.employeeId);
return builder.toString();
}

/**
* Simple object equality comparison method.
*
* @param obj Object to be compared to me for equality.
* @return {@code true} if the provided object and I are considered equal.
*/
@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Employee other = (Employee) obj;
if (!Objects.equals(this.employeeId, other.employeeId))
{
return false;
}
return true;
}

/**
* Hash code for this instance.
*
* @return My hash code.
*/
@Override
public int hashCode()
{
int hash = 3;
hash = 19 * hash + Objects.hashCode(this.employeeId);
return hash;
}
}
Main.java (Version 1)

package dustin.examples;

import static java.lang.System.out;

/**
* Simple class enabling demonstration of ToStringBuilder.
*
* @author Dustin
*/
public class Main
{
/**
* Main function for running Java examples with ToStringBuilder.
*
* @param args the command line arguments
*/
public static void main(String[] args)
{
final Person person = new Person("Washington", "Willow");
out.println(person);
final Employee employee = new Employee("Lazentroph", "Frank", "56");
out.println(employee);
}
}

The above example is simple and its output is shown next:

The output depicted above shows the String in question printed for both instance's output generated by ToStringBuilder. The String representation of the instance of Person class includes the String "1f5d386" and the String representation of the instance of Employee class includes the String "1c9b9ca". These strings are the hexadecimal representation of each object's identity hash code.

The strings "1f5d386" and "1c9b9ca" do not look like the integer hash codes many of us are used to seeing because of their hexadecimal representation. The Integer.toHexString(int) methods [available since JDK 1.0.2] is a convenience method for printing an integer in hexadecimal format and can be used to convert "normal" hash codes to see if they match those generated by ToStringBuilder. I have added calls to this method on the instances' hash codes in the new version of the Main class.

Main.java (Version 2)

package dustin.examples;

import static java.lang.System.out;

/**
* Simple class enabling demonstration of ToStringBuilder.
*
* @author Dustin
*/
public class Main
{
/**
* Main function for running Java examples with ToStringBuilder.
*
* @param args the command line arguments
*/
public static void main(String[] args)
{
final Person person = new Person("Washington", "Willow");
out.println(person);
out.println("\tHash Code (ten): " + person.hashCode());
out.println("\tHash Code (hex): " + Integer.toHexString(person.hashCode()));

final Employee employee = new Employee("Lazentroph", "Frank", "56");
out.println(employee);
out.println("\tHash Code (ten): " + employee.hashCode());
out.println("\tHash Code (hex): " + Integer.toHexString(employee.hashCode()));
}
}

Executing the above leads to the following output:

As the output indicates, the hexadecimal representation of the hash code for the Person instance does indeed match that shown in the ToStringBuilder-generated String for that instance. However, the same cannot be said for the Employee instance. The difference is that the Person class does not override the hashCode() method and so uses the identity hash code by default while the Employee class does override its own hashCode() (and therefore being different than the identity hash code).

The third version of Main outputs the identity hash code using System.identityHashCode(Object) [discussed in further detail in my blog post Java's System.identityHashCode].

Main.java (Version 3)

package dustin.examples;

import static java.lang.System.out;

/**
* Simple class enabling demonstration of ToStringBuilder.
*
* @author Dustin
*/
public class Main
{
/**
* Main function for running Java examples with ToStringBuilder.
*
* @param args the command line arguments
*/
public static void main(String[] args)
{
final Person person = new Person("Washington", "Willow");
out.println(person);
out.println("\tHash Code (ten): " + person.hashCode());
out.println("\tHash Code (hex): " + Integer.toHexString(person.hashCode()));
out.println("\t\tIdentity Hash (ten): " + System.identityHashCode(person));
out.println("\t\tIdentity Hash (hex): " + Integer.toHexString(System.identityHashCode(person)));

final Employee employee = new Employee("Lazentroph", "Frank", "56");
out.println(employee);
out.println("\tHash Code (ten): " + employee.hashCode());
out.println("\tHash Code (hex): " + Integer.toHexString(employee.hashCode()));
out.println("\t\tIdentity Hash (ten): " + System.identityHashCode(employee));
out.println("\t\tIdentity Hash (hex): " + Integer.toHexString(System.identityHashCode(employee)));
}

With this in place, we can now compare the the identity hash code to the string generated by ToStringBuilder.

The last example definitively demonstrates that ToStringBuilder includes the hexadecimal representation of the system identity hash code in its generated output. If one wants to use the hexadecimal representation of the overridden hash code rather than of the identity hash code, an instance of ToStringStyle (typically an instance of StandardToStringStyle) can be used and the method setUseIdentityHashCode(boolean) can be invoked with a false parameter. This instance of ToStringStyle can then be passed to the ToStringBuilder.setDefaultStyle(ToStringStyle) method.

As a side note, the equals(Object) and hashCode() methods in the Employee class shown above were generated automatically by NetBeans 7.1. I was happy to see that, with my source version of Java for that project specified as JDK 1.7, this automatic generation of these two methods took advantage of the Objects class.

I have used ToStringBuilder-generated output throughout this post to facilitate discussion of hexadecimal representations of identity hash codes, but I could have simply used the JDK's own built-in "default" Object.toString() implementation for the same purpose. In fact, the Javadoc even advertises this:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

The only reason I did not use this example to begin with is that I almost always override the toString() method in my classes and do not get this "default" implementation. However, when I use ToStringBuilder to implement my overridden toString() methods, I do see these hexadecimal representations. I am likely to reduce my use of ToStringBuilder as I increase my use of Objects.toString().

Many of us don't think about hexadecimal representations or identity hash codes in our daily Java work. In this blog post, I have used ToStringBuilder's output as an excuse for looking a little closer at these two concepts. Along the way, I also briefly looked at the Integer.toHexString(Object) method, which is useful for printing numbers in their hexadecimal representation. Knowing about Java's support for hexadecimal representation is important because it does show up in toString() output, in labeling of colors, memory addresses, and in other places.

Thứ Ba, 13 tháng 3, 2012

Typesafe Stack 2.0 Released: Q&A with Typesafe President and CEO

Typesafe issued a press release today including this initial paragraph:

Typesafe today announced the release of Typesafe Stack 2.0, the latest version of its open source software stack. Typesafe Stack 2.0 is a comprehensive platform for building applications in Java and Scala that can scale to the largest workloads in cloud computing and virtualized enterprise datacenter environments. The release adds the innovative Play web framework for the first time, and includes Akka event-driven middleware 2.0, with significant enhancements for building concurrent and distributed applications.

This newly released Typesafe Stack 2.0 might provide a nice way to introduce oneself to Scala while addressing modern development needs. I've long felt the best way to learn a new language, framework, or library is to use it in a practical situation. Jan Machacek made a similar point in the JavaWorld article Learn Scala with Specs2 Spring, where he discussed learning Scala as one used it with his company's Specs2 Spring Extension.

Because I'm new to Play, Akka, and even Scala, I welcomed the opportunity to ask the folks at Typesafe questions about the Typesafe Stack 2.0 from a beginner's perspective. The following questions were asked of and answered by Typesafe President and CEO Donald Fischer. With these questions, I tried to find out what I needed to know to determine the motivation for beginning use of Typesafe Stack 2.0 and where to start in my efforts to learn and use it.

Q&A with Typesafe CEO Donald Fischer

Question: What are the most compelling advantages of the Typesafe Stack 2.0?

Some of the most compelling advantages of the Typesafe Stack versus legacy platforms are:

  • Strategies for working in a world of horizontal scale. Modern software needs to take advantage of more cores and more machines, rather than faster single cores.
  • An emphasis on developer agility, productivity, and enthusiasm. Developers want to work quickly and focus on business logic rather than boilerplate.
  • Fewer bugs. The Typesafe Stack has tools to avoid bugs up front. For example, Akka helps you avoid tricky thread synchronization issues, and Scala helps you write side-effect-free, typesafe code with fewer opportunities for error.
  • An emphasis on pragmatic interoperability. The Typesafe Stack APIs can be used from Java or Scala or both; and they can be adopted incrementally. It's as simple as adding some jars to your project.
Question: How much familiarity with Scala is required to use Typesafe Stack 2.0?
While the Typesafe Stack includes Scala, and is built on a Scala foundation, both the Play web framework and Akka middleware offer native APIs for both Java and Scala. So developers can build applications that leverage all of the capabilities of the Typesafe Stack without any specific knowledge of Scala (though we don't think they'll be able to resist the added productivity that Scala provides once they get a taste).
Question: On a spectrum of 100% Java to 100% Scala with a combination of the two between those ends of the spectrum, what portion of the spectrum is supported by Typesafe Stack 2.0? (Can one use Typesafe Stack 2.0 with Java only?)
100% of the functionality in the Typesafe Stack frameworks (Akka and Play) is supported for both Scala and Java.
Question: What is the easiest way to get started using the overall Typesafe Stack 2.0?
We've put together a Getting Started Guide, here: http://typesafe.com/resources/getting-started/
Question: What online resources are available regarding the use of Typesafe Stack 2.0?
We've collected a variety of resources including videos from project contributors, commercial users, and the community here: http://typesafe.com/resources
Question: Are there any books available or planned that cover the individual products within Typesafe Stack 2.0 as well as the overall integrated stack?
Yes, we've accumulated a collection of books here: http://typesafe.com/resources/books We're proud that several of these books are authored by Typesafe employees, including Martin Odersky, Josh Suereth, Heiko Seeberger, and Philipp Haller.
Question: What is the licensing for Typesafe Stack 2.0 and is it consistent across the individual products and the overall stack?
The Typesafe Stack is 100% open source. It's complemented by the commercial Typesafe Subscription, which adds support, maintenance, and tools including the new Typesafe Console. The Typesafe Console is available exclusively to Typesafe Subscription customers.
Question: What potential enhancements are planned for Typesafe Stack 2.0?
Upcoming releases of the Typesafe Stack will include additional clustering features and enhanced support for building applications that adapt to elastic cloud environments.

Screen Images

I was provided with some images that I have posted next. Note that these display the Typesafe Console, which is only available via the Typesafe Subscription option.

My Own Thoughts and Observations

Typesafe Stack 2.0 appears to offer developers several advantages, one of which is the ability to learn the Scala language, the Play framework, and the Akka toolkit all while solving difficult problems associated with modern software development. The press release alludes to these problems in the sentence, "Typesafe provides the most scalable software platform designed for the computing architectures of the future -- multicore, parallel and cloud applications."

Typesafe's licensing model is a familiar one with significant product (the Typesafe Stack 2.0) available via an open source license and add-on tools available for a commercial subscription. The advantage of this is that a developer can "play" (no pun intended) with Typesafe Stack 2.0 and then later move to Typesafe Subscription as needed and desired. It has been my experience that, generally speaking, it is an advantage to have a large corporate sponsor of an open source product I am using. Corporate sponsorship tends to mean dedicated resources invested in improving and maintaining the product. Examples include the Spring Framework and Groovy (SpringSource), NetBeans and GlassFish (Sun/Oracle), Eclipse (IBM), etc. Typesafe's optional commercial support for Typesafe Stack 2.0 is potentially useful for customers, but Typesafe's apparent commitment to the product's development and maintenance is highly valuable as well.

Specific licensing information for the products of Typesafe Stack 2.0 can be found at the Typesafe Licenses page. As of this writing, this page reports that "Scala and the Scala IDE for Eclipse are available under the Scala License", Play and Akka are licensed with the Apache License, Version 2.0, and "Simple Build Tool (sbt) is available under the BSD license."

Conclusion

The press release, the answers to my questions above, and the plethora of resources available on the Typesafe site all imply a highly beneficial product. I am not in any way affiliated with Typesafe and I have not yet tried Typesafe Stack 2.0 out for myself, but it looks very promising. If nothing else, playing with it and possibly applying it to real problems might be one of the best ways to learn Scala, Play, and Akka, but one can always fall back to Java when using it if necessary.

Thứ Bảy, 10 tháng 3, 2012

JavaOne 2012 Call for Papers

The JavaOne 2012 Call for Papers has been issued. The window for submission is March 14 through April 9. Notifications regarding accepted and declined proposals will be made in late May or early June and speakers whose proposals are accepted are expected to confirm their session by the middle of June. JavaOne 2012 is September 30 through October 4, 2012, in San Francisco, California. JavaOne 2012 is again being held in conjunction with Oracle OpenWorld 2012 and OpenWorld begins its call for papers on March 14 as well.

Thứ Năm, 8 tháng 3, 2012

How Badly Do We Want a New Java Date/Time API?

The current Java.net poll question is, "How critical is it for JSR-310 (new Date and Time API) to be implemented in Java 8?" At the time of my writing of this post, nearly 150 respondents have voted and an overwhelming percentage have answered either "Very" (53%) or "It would be nice, but we can get by using the current classes" (22%). With 3/4 of the respondents feeling that it would either "be nice" or is "very important" to get a new Java Date/Time API, I think it's safe to say that Java's current Date and Calendar approach has not grown on us. Perhaps my biggest surprise so far with the survey results is that 2% of the respondents have stated, "I prefer the current date and time classes." Maybe that's from the people who wrote those classes?

I tend to use Java's date/time/calendar APIs off and on. When I use them, I really don't like them, but do start to tolerate them. I begin to forget how much I loathe them until I use them again. I recently helped a colleague familiar with Java (but not with the date/time APIs) to understand how to do some Date/Calendar/String manipulation and presentation. Explaining this mess out loud to him made the ridiculous difficulty of using these too-flexible APIs even more obvious to me. I could see on his face that he was thinking I was either kidding him or didn't know what I was talking about. Although I've gotten to the point where I can make them make do, it's much more difficult than it should be.

Much has been written about the woes of date/time handling in Java. Rob Sanheim wrote in 2006 about date/time-related problems in three of his Top Five Worst APIs in Java (Calendar, Date, and DateFormat/SimpleDateFormat). Java's Date-handling is focused on in Cameron Purdy's 2005 post The Seven Habits of Highly Dysfunctional Design. Tero Kadenius reminded us in the 2011 post Handling dates in Java that "The date/time API in Java is notoriously painful to work with." The aptly named post Java Dates Still Suck was published in 2009.

The current Java.net survey confirms my feeling after working with numerous Java developers and after reading many blogs and articles that the vast majority of Java developers are anxious to get a better standardized way of handling dates and times in Java.

Thứ Hai, 5 tháng 3, 2012

NetBeans 7.1's Internal Compiler and JDK 6 Respecting Return Type for Method Overloading

I was first exposed to Java after several years of C++ experience and so it seemed natural when I learned that Java does not allow method overloading based on return type. The Defining Methods section of the Classes and Objects lesson in the Java Language Tutorial states, "The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type." Indeed, as Vinit Joglekar has pointed out, "It is an accepted fact that Java does not support return-type-based method overloading." The StackOverflow thread Java - why no return type based method overloading? explains why this is the case in Java. Given this, I was surprised when a colleague showed me a code snippet with two overloaded methods with the same runtime signature that compiled in JDK 6 as long as the return types differed.

The following class compiles successfully with JDK 6, but not with JDK 7.

Compiles in JDK 6 But Not in JDK 7

package examples.dustin;

import java.util.Collection;

/**
* Simple example that breaks in Java SE 7, but not in Java SE 6.
*
* @author Dustin
*/
public class Main
{
public static String[] collectionToArray(final Collection<String> strings)
{
return new String[] { "five" };
}

public static int[] collectionToArray(final Collection<Integer> integers)
{
return new int[] { 5 };
}

/**
* Main function.
*
* @param arguments The command line arguments; none expected.
*/
public static void main(String[] arguments)
{
}
}

As described in Angelika Langer's What Is Method Overloading?, the above code should not compile. It doesn't in Java SE 7. In NetBeans 7.1, it doesn't. Or, more properly, it's a mixed bag.

As the screen snapshot below demonstrates, NetBeans 7.1 builds the source code above fine as shown in the Output Window when the version of Java associated with the project is Java SE 6. However, the NetBeans editor shows the red squiggly lines indicating compiler error. The next image shows what the error message is.

Although NetBeans 7.1 is able to build the code shown above when it's part of a project associated with Java SE 6 (Update 31 in this case), the code editor still reports the error shown above. This is because NetBeans uses a different version of the Java compiler internally than the one explicitly associated with the project being edited. If I change the version of Java associated with the NetBeans project for the source code above, it will no longer build in NetBeans. This is shown next.

There are a couple interesting things about this bug. First, the fact that this code compiles fine in Java SE 6 but is addressed and does not compile in Java SE 7 means that it is possible for code working in Java SE 6 to not work when the code base is moved to Java SE 7. I downloaded the latest version of JDK 6 available (Java SE 6 Update 31) and confirmed the original code shown above still builds in Java SE 6. It does not build in Java SE 7.

There are other versions of the code above that do not build in Java SE 6 or in Java SE 7. For example, if the code above is changed so that the methods return the same type, the code doesn't build even in Java SE 6. Similarly, if the Collection parameters to the two overloaded methods include a "raw" Collection (no parameterized type), it won't compile in Java SE 6 either. Of course, even if the return types are different, if the same Collection parameterized types are passed to both overloaded methods, even Java SE 6 won't compile this. These three situation are depicted in the following three screen snapshots.

The code that builds in Java SE 6 but not in Java SE 7 needs to have overloaded methods that differ in both return types and in terms of the parameterized types of the collections that make up their method parameters. It doesn't matter if a given return type matches or is related to the parameterized type of the method's parameter as long as they differ. If the return types are the same, Java SE 6 detects a compiler error. Java SE 6 also detects the error if the erased parameters boil down to the same collection after erasure and the return types are not different.

A second interesting thing about this bug is how its handled in NetBeans. Because NetBeans use its own internal compiler that does not necessarily match the version of the compiler that the developer has associated the IDE project to, you can run into situations like this where the code actually builds in the IDE, but the IDE's functionality such as code editors and project browsers indicate the code breaking.

Because NetBeans 7.1 uses its own internal Java compiler for the code editor, one might wonder if this means Java 7 features could be sneaked in and would work in the IDE but then would not build when attempted from the command line or when explicitly built in the IDE. The next screen snapshot demonstrates why that is not the case. In that snapshot, a Java 7 specific feature is in the code and NetBeans 7.1 properly warns that this is not compatible with the Java 1.6 source setting.

Bug 6182950 (methods clash algorithm should not depend on return type) has addressed the issue in JDK 7, but not in JDK 6. A related bug is Bug 6730568 ("Type erasure affects return types + type parameters"). Three additional references that provide sufficiently more background details are two StackOverflow threads (Differing behaviour between Java 5 & 6 when overloading generic methods and What is the concept of erasure in generics in java?) and the Java Tutorial entry on Type Erasure.

The colleague who showed me this issue realized its existence because NetBeans 7.1 reported the "name clash ... have the same erasure" even when he was working with Java SE 6 code. This discovery was "accidental" due to the newer version of NetBeans using Java SE 7 compiler internally, but he welcomed the opportunity to fix the issue now rather than when he migrates to Java SE 7.

I found this issue worth posting a blog post on because it provides a warning about a bug that may already be in some Java SE 6 code bases but will be made all too evident when the code base is moved to Java SE 7. I also posted this because I think it's important to be aware that modern versions of NetBeans use an internal compiler that may be of a different version than the compiler the developer has explicitly associated with his or her NetBeans project.

Thứ Sáu, 2 tháng 3, 2012

Useful Lesser Known Java Classes

A recent reddit Java thread is titled "Share a useful class from the standard Java Class Library!" and starts with the comment, "There are so many available classes and sometimes ones exist that you don't realize. Share one that you use that the rest of us may not be aware of!" In this post, I look at some of the (mostly JDK) classes mentioned in the forty (at time of this writing) responses to this request.

Several respondents provided concurrency-related Java classes such as Executors, java.util.concurrent.CountDownLatch, java.util.concurrent.atomic.AtomicInteger, ThreadLocal, and "anything in the packages" java.util.concurrent and java.util.concurrent.atomic.

Several classes related to String manipulation are mentioned in this thread. These include StringBuffer, and StringBuilder. I have blogged about these String-related classes in the post String, StringBuffer, and StringBuilder: There Is A Performance Difference. Other String-related classes mentioned in this thread include java.util.StringTokenizer and Apache Commons' StringUtils (which is mentioned in my post Checking for Null or Empty or White Space Only String in Java). The java.util.Scanner class also receives mention for making text parsing easier.

In the area of user interface work, java.awt.geom package is mentioned as are java.awt.Desktop and javax.swing.SwingUtilities. The class java.awt.Point is highlighted with an explanation that concludes, "But any two int pairs work and easier to pass to/from a function (instead of an array or whatever)." I could have used it instead of my own nested Coordinate class or instead of the JavaFX javafx.util.Pair class when crafting a JavaFX Christmas tree. The class java.awt.Robot is also mentioned in the thread and I have discussed that class in the post Screen Snapshots with Java's Robot.

Not surprisingly, several Java collections make the list. These include java.util.EnumSet and EnumMap (see my post The Sleek EnumMap and EnumSet), java.util.ArrayDeque (see my post The Java SE 6 Deque), java.util.PriorityQueue, java.util.Arrays, and java.util.Collections (see my post The Java Collections Class).

In my opinion, java.lang.ClassLoader, java.util.ServiceLoader, and java.nio.file.FileVisitor are some of the more elaborate and specialized classes mentioned in the reddit Java thread. Many of us use strong references by default, but java.lang.ref.WeakReference and java.lang.ref.SoftReference receive mention in this thread as well.

Finally, a class and a method that are referenced that I often use are the BigDecimal class (one of my many posts alluding to this class is Caution: Double to BigDecimal in Java) and the method System.nanoTime().

Conclusion

The reddit/Java thread Share a useful class from the standard Java Class Library! represents ideas from the Java community regarding lesser known useful Java classes generally available in the JDK. I liked many on the list and can think of additional examples as well (and likely more will appear from other posters). In particular, I think JDK 7's Objects class is mighty useful and less known than it should be. I also agreed with one of the responses which stated, "Add the google guava library for tons of useful classes" and have written several posts on Guava.