Mar 20 2007

Class HighLite Collections

When working with the Java Collections API, you often need to sort, shuffle, or reserve a list. For these and other tasks you can use a class aptly named Collections made available in the java.util package. The Collections class is like the Math class in that it provides a large number of static methods. The Collections class provides convenience static methods for working with any of the Collections API classes such as List, Map, and Set. For this Class HighLite I want to focus on the methods that make an immutable, synchronized, or singleton collection.

Immutable Lists
Item 13, Favor Immutability, in Joshua Bloch’s book Effective Java describes the benefits of writing and using immutable classes, that classes whose instances cannot be modified after creation. In general, immutable objects tend to be thread safe. In my experience, I have seen far too many insidious bugs related to cached/global/singleton mutable objects. These bugs usually happen because some code updates a global object which in turn invalidates the state of another resource. As a rule of thumb, I never cache, pool, or use as singleton mutable objects.

Creating immutable classes is easy if you are dealing with Strings (immutable) and primitives values. If you are dealing with any of the Collections API classes such as list, map, or set, you need to make that collection unmodifiable. Here is how to return an immutable list back to a calling code block.

[source:java]
public List getFieldNames() {
return Collections.unmodifiableList(this.fieldnames);
}
[/source]

Trying to modify an unmodifiable list by adding, setting, removing values would generate a run time exception, UnsupportedOperationException.

Synchronized Sets
Synchronized objects provide an additional level of thread-safety. The Collections class can provide a synchronized collections wrapper for any list, map, or set. One word of caution, you still need to call synchronized keyword on a synchronized wrapper to your list. That last sentence might be a bit confusing, so let me try to clarify it with some code.

[source:java]
List syncSet = Collections.synchronizedSet(myStringSet);
synchronized(syncSet) {
for(Iterator i = syncSet.iterator(); i.hasNext(); ) {
String str = (String)i.next();
}
}
[/source]

Singleton Maps
The Java Collections class has a series of methods to create a ‘singleton’ set, list, and map. A singleton collection object is immutable and has just one value. Here is an example of a singleton map.

[source:java]
Map map = Collections.singletonMap(myKey, myValue);
[/source]

Since the above singleton map is immutable, it will throw an UnsupportedOperationException when you try to put new values into the map.

Technorati Tags: , , , , , , ,


Mar 16 2007

Advanced JavaOne Conference Guide

I just received an advanced copy of JavaOne 2007 conference guide. The guide is by no means final. I still have not received my pass, I am actually finalizing approval from the old corporate ball and chain, my boss. In trying to present my case for going to JavaOne, I spent some time highlighting the presentations that I want to attend. Here is the run down of what looks interesting to me.

JAVA SE Track
TS 2294 Closures for the Java Programming Language – Neal Gafter of Google will describe his researching in bringing closures into the the next release of the Java programming language.

TS 2689 Effective Java Reloaded: This Time It’s for Real – If you haven’t read Effective Java, do so immediately. This book belongs next to the GoF Design Patterns book in every Java developers bookshelf. Last year Joshua gave a presentation with the similar name, Effective Java Reloaded, that covered Java 5 constructs.

Desktop Track
TS 3165 Filthy-Rich Clients: Talk Dirty to Me – Chet Haase and Romain Guy gave a presentation with the same name at JavaPolis 2007. There is a video presentation available here. Chet and Romain basically talked about linear gradients, alpha composites, timers and timing framework, animation, JOGL, and more.

TS 3420 Form Follows Function (F3) – I have been following along the great examples of F3 that Christopher Oliver has been releasing on his blog. I can’t wait to get started on F3. F3 is a scripting language for the JVM with great 2D/SVG graphics support.

TS 3569 Beans Binding – This session sounds like a data binding discussion dealing in specific with JSR 295: Beans Binding. Last year I went to a Desktop Patterns and Data Binding that basically said that there is no great data binding framework.

TS 3834 Being Productive with Swing – Anything that helps me be more productive in Swing has my attention. You can do some great UI with Swing if you use it beyond just adding JButtons to a container. Have you ever thought of writing your own layout manager? That almost sounds like an interview question.

TS 3942 JSR 296: The Swing Application Framework – I am really looking forward to Hans Muller and Joshua Marinacci give a demo of the Swing Application Framework.

Java EE Track
TS 4902 Java Persistence API: The Best Practices and Tips – The conference guide states that this session will cover the basics for high-performance persistence, generated primary keys, bulk update/deletes, mapping objects to data, and more.

The Next Generation Web Track
TS 6039 Building a Web Platform: Java Technology at Ning – Ning employees are will present on their experience with making your platform scriptable.

TS 6375 jMaki: Web 2.0 App Building Made Easy – From the conference guide, “jMaki is a lightweight client-server framework for creating JavaScript … applications using CSS layouts.”

TS 6503 JRuby, Rails, and Java EE – Another JRuby/Rails session. This session will be presented by Tim Bray of Sun. Tim spoke at the RubyConf 2006 on I18N/M17N and Unicode and I thought he was a great speaker. I am looking forward to hear his presentation.

Open Source Track
TS 7082 Building JavaServer Faces Applications with Spring and Hibernate – I think Hibernate is a great piece of technology and I have been wanting to get into Spring.

TS 7361 Writing Java Platform Applications for Ubuntu – A panel of professionals from Ubuntu, Sun, and Canonical will present on releasing applications through and for Ubuntu. Ubuntu is currently one of the most popular Linux distributions.

TS 7557 OpenOffice.org Extensions with NetBeans Software – At my current position I have had write code, plugins, add-ins, scripts, etc. to integrate with Microsoft Office, including Outlook. It would be great if I could offer the same integration point for OpenOffice.

Tools and Languages Track
TS 1742 Cool Things You Can Do with the Groovy Dynamic Language – It looks like this session will cover such Groovy things as XML/UI builders, COM Scripting, and more.

TS 9086 Advance JRuby: Metaprogramming Magic Unleashed – Charles Nutter, the force behind JRuby, will be presenting about JRuby metraprogramming.

TS 9370 JRuby on Rails: Agility for the Enterprise – Ruby on Rails will get into enterprise environments through JRuby. Thomas Enebo and Charles Nutter, both from Sun, will describe how this will happen.

TS 9516 Using jMaki in a Visual Development Environment – This sounds like another jMaki/NetBeans technical session.

TS 9535 Comparing the Developer Experience of Java EE 5.0, Ruby on Rails, and Grails: Lessons Learned from Developing One Application – I haven’t seen much on Grails in this advance conference guide. I hope there is more on Grails at JavaOne.

TS 9555 Quick and Easy Profiling with Integrated Tools – Every time I have had to profile a Java application for memory leaks it has been in a tight schedule. I know need to be up to date with the latest tools and techniques of Java profiling.

TS 9720 Advanced Groovy – I believe Rod Cope has given a Groovy presentation at JavaOne like three years in a row. Last year his talk was named something like Groovy = Java Tech + Ruby + Python for the JVM.

From what I noticed from this advance guide it that a big theme at JavaOne 2007 will be JRuby. Another themes which will continue from last year will Java Persistence API, Web 2.0/Ajax, and Groovy/Grails.

Technorati Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


Mar 10 2007

Software Project Management with Maven 2

The one development tool that I use every single day, aside from Eclipse, is Maven. Maven is a software project management tool developed by the Jakarta peeps at the Apache Software Foundation. Maven allows me to build, test, and package our entire Java application in one command. Our application is a proprietary Rapid Application Framework made up of over four thousand Java classes, hundreds of JSP files, dozens of JavaScript files, and tons of XML-based screens (not unlike Mozilla’s XML User Language). Of course, an application our size is broken down into several modules/components and requires a lot of third party jars. Maven grew out of a similar situation at Jakarta.

Maven’s objective says it all, “Maven’s primary goal is to allow a developer to comprehend the complete state of a development effort in the shortest period of time.” In my development experience, I have seen Java applications built with cryptic PERL scripts and series of Ant build files. Using Maven has been the most pleasant build tool experience to date.

In my opinion, Maven does not requires a big learning curve or large investment in time to get started. You should be able to get started by the time you finish skimming this document.

Maven Setup
In a Windows system, lets imagine you unzip maven to c:\maven. In this situation you will need to add C:\maven\bin to your system %PATH% environment variable. In Windows you can do this via the Advanced tab of the System Properties dialog.

In Mac OS X, if you placed maven in /maven, add /maven/bin to you $PATH variable. In Mac OS X you can add a line to your .bash_login that reads as the following.

export PATH="/maven/bin:$PATH"

In both operating systems, make sure you have defined a JAVA_HOME environment variable that points to your JDK. The JAVA_HOME variable is required by Maven.

Once ‘installed’ you can execute the following command from you command prompt.

mvn --version

As of this writing, the current Maven version is 2.0.5, you might see a different Maven version.

Create New Project
To create a new Maven project execute the following Maven goal.

mvn archetype:create -DgroupId=com.juixe.app -DartifactId=my-app

A brief explanation is in order. The archetype:create is a Maven goal to build a new project. The groupId is a Java system property the defines the base package for the new project. The artifactId defines you Maven project/artifact name. Maven will create a directory for the project named with the value of artifactId property.

The above Maven goal will create a sample Java project with a hello world App.java and AppTest.java source files under a newly created my-app directory. Take a moment to step through the newly created files and directories.

Maven Goals
Similarly to how Ant has tasks, Maven uses goals. Maven has goals to clean, compile, test, and package a Java project.

If you created the my-app project above, cd to the my-app directory. Under the my-app directory execute the following command from the prompt or terminal.

mvn package

With the above command, Maven will compile, test, and jar the project. You should see a BUILD SUCCESSFUL. At the end of every single build, I look for that message in the prompt.

The most common command I execute is the clean compile.

mvn clean compile

One thing to note is that the project jar, compiled classes, and any other generated documents and files will be placed under the my-app\target directory.

Project Dependencies
An typical Java project will use external third party libraries. As an example, lets say our application makes good use of the Jakarta Commons-CLI library. We denote this dependency to Commons-CLI by adding the following configuration in the Project Object Model file, pom.xml.

<dependency>
  <groupId>commons-cli</groupId>
  <artifactId>commons-cli</artifactId>
  <version>1.0</version>
  <scope>compile</scope>
</dependency>

Many of the most popular and useful jars are hosted by Apache and/or Ibiblio. For jars hosted on these repository sites, Maven will discover them and download them. For jars not hosted on these repository sites, you will need to download them yourself and place them in a centralized location for Maven to discover.

Managing Multiple Projects
The one reason that I choose Maven, over other build tools such as Ant, is that it easily allows me to build multiple projects with a single command. Maven allows you to group multiple projects and define their dependencies. This feature allows you to create a Maven project for each logical component in your Java application.

The Maven documentation has a great tutorial, with the necessary XML configurations, to group two or more dependent projects. Once you have grouped multiple projects together you can compile, test, and/or package them with a single Maven goal.

Java 1.5
If your Java source files are written using Java 5 code, then you will need to update the build configuration in the Project Object Model file. Add the following bit of XML to your pom.xml.

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>1.5</source>
        <target>1.5</target>
      </configuration>
    </plugin>
  </plugins>
</build>

If you are managing multiple projects, you can place the above XML in the parent pom.xml to affect all other child modules.

IDE Projects
Another great feature of Maven is that once you have defined you Maven projects and their inter-dependencies you can then create an IDE project. To create an Eclipse project execute the following command.

mvn eclipse:eclipse

For an IntelliJ IDEA project, try the following command.

mvn idea:idea

For a NetBeans project, try the following command.

mvn netbeans-freeform:generate-netbeans-project

Maven Repository
One thing to note is that Maven downloads a lot of jars and places them in the Maven repository. The Maven repository is located in your user home directory. In Windows, the Maven repository is located under C:\Documents and Settings\<username>\.m2. In Mac OS X, you can find the Maven repository under ~/.m2.

If you create a project for your favorite IDE you will need to add a M2_REPO variable to point to Maven repository. In Eclipse, to add the M2_REPO variable select Window > Preferences > Build Path > Classpath Variables. Add the new M2_REPO classpath variable and set it to the Maven repository folder location, C:\Documents and Settings\<username>\.m2\repository.

Technorati Tags: , , , , , , , , , , , ,


Mar 8 2007

Scan Your Ports

There comes a time in a developer’s life that the he needs to scan his own ports. I recently had to do this because some process, other than my JBoss Application Server was hogging the port 1099. I kept getting a JVM_Bind error when I started the application server because the port was in use but I couldn’t figure out what process was using that port. Usually when I have a JVM_Bind error I just kill all Java processes, but in this case I didn’t have any Java programs running. In the end, after scanning my ports, I found out that Skype had port 1099 in use.

To scan your which ports are in use in you development machine you can use TCPView from Microsoft. TCPView is part of Microsoft’s Windows Sysinternals utilities.

If you are a prompt type of of person and you have MKS NT or Cygwin you can use the following command to find out what process is using port 1099.

netstat -ao | grep 1099

Technorati Tags: , , , , , , , , ,


Mar 2 2007

SV RoR February Meetup

Recently I attended that February 2007 Silicon Valley Ruby on Rails meetup at the offices of Insider Pages. At this month’s meeting, Scott Persinger gave a presentation of vod:pod and Matt Whittaker talked about his solo efforts with My Free Copyright.

According to Scott of vod:pod, vod:pod is another video space social network user generated content based web application. Think of vod;pod as a hyper-aggregation social recommendation site for video powered by good ol’ Rails and Ajax. Scott also informed those railers in attendance that a team of 2 software engineers went from conception to deployment in about 6 months. According to Scott, vod:pod uses the best Rails bits such as migrations, active record, plugins, Ajax + Prototype. Scott listed RJS, Hpricot + Mechanize, and IO.popen_timeout. As for Rails annoyances he lists the lack of better page component support, poor IDE debugging options, that classes never close, and poor library support.

As for the business model for vod:pod, Scott said that they could be running ads and they be making $3/month but at this point they don’t want to hamper the users experience. It seems that to the team at vod:pod they aren’t to concern about a business model until they start to scale up.

The second speaker of the night was Matt of My Free Copyright, a copyright registry for digital content. Matt’s talk just listed the ingredients for a typical Ruby on Rails web application. Matt recommended Acts as Authenticated as the first Rails plugin to get your app up and running. Matt also described some of the pros and cons of using the file, database, and memcache session manager. From what I gather, he recommends you start off with SQLSessionStore since memcache has “more moving parts.” Matt closed his discussion of with some background on BackgrounDRb (pun intended). Think of BackgrounDRb as a cron server that allows you to schedule tasks.

Technorati Tags: , , , , , , , , , , , , , , , , , , , , ,


Feb 28 2007

Rails Performance Link Fest

I have read most of the articles out there regarding Rails performance. Performance-minded railers list fragment caching, normalize database design, proper use of indices, and the exclusion of unnecessary columns from large tables in active record models as providing a beneficial performance boost for any Rails application. These railers also warn against excessive use of route url recognition and generation, eager loading, and slow application helpers.

The following list is a collection of the best articles, blog posts, presentations and discussions on Rails performance. Feel free to add any site that I might have missed in the comments!

Rails Performance Tips
Common Performance Problems in Rails – Pros and con between SQLSessionStore and MemChacheStore session containers, tips on optimizing queries, and general information regarding how to avoid slow helpers.
The Adventures of Scaling: Stage 1, Stage 2, Stage 3, Stage 4 – A detailed explanation a Rails production architecture.
Optimizing Rails Resource Usage – A short list of top Rails optimization tips, which include the proper use of caching.
Sustainable Performance with Ruby on Rails – A 58 page PDF presentation describing railsbench, caching, session performance, and efficient Ruby code.
Rails performance tips – A discussion on eager loading, excluding unnecessary columns, indexing database columns, and caching.
Top 10 Ruby on Rails performance tips – Provides great tips to optimize your ruby code and how to handle finders.
Performance related changes in Rails 1.1 – Discussion of performance enhancements in rails 1.1.
Rails performance and caching, Part 2 – A discussing of Rails performance using caching.
Stefan Kaes – Rails Performance – RubyConf 2006 conference notes on the Rails Performance presentation given by Stefan Kaes.
Stefen Kaes – Optimizing Rails – Another post on the Rails 2006 presentation by Stefan Kaes on Rails Performance.
Rails performance with FastCGI and Apache – A blog post on performance with Apache.
Rails Performance Tool Box – A list of tools that come in handy when optimizing a Ruby on Rails application, which include query analyzer, query trace, and mtop.
Rails Caching Documentation – Documentation for action, page, and fragment caching.
The effect of using Rails fragment caching – Goes over the performance boost of using fragment caching.

Rails Performance Tools
Query Builder Plugin – Bypass the overhead of construct_finder_sql.
QueryTrace Plugin – Helps to identify the location/caller of bad queries.
MySQL Query Analyzer Rails Plugin – Helpful to analyze SQL queries.
Rails Log Analyzer – Reads the Rails log files and exposes potential points of optimization.
Railsbench – “A small collection of ruby and shell scripts which make measuring raw performance of rails apps a snap.”

Technorati Tags: , , , , , , , , , , , , , , ,