<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>JavaWorld's Daily Brew</title>
  <subtitle>Starting conversations in the Java developer community</subtitle>
  <link rel="alternate" type="text/html" href="http://www.javaworld.com/community"/>
  <link rel="self" type="application/atom+xml" href="http://www.javaworld.com/community/atom/feed"/>
  <id>http://www.javaworld.com/community/atom/feed</id>
  <updated>2009-07-04T20:56:26-04:00</updated>
  <entry>
    <title>Diagnosing and Resolving StackOverflowError</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3153" />
    <id>http://www.javaworld.com/community/node/3153</id>
    <published>2009-07-04T19:04:00-04:00</published>
    <updated>2009-07-04T20:56:25-04:00</updated>
    <author>
      <name>dmarx</name>
    </author>
    <category term="Dustin" />
    <category term="Java (General)" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>A recent <a href="http://www.javaworld.com/community/">JavaWorld Community</a> forum message (<a href="http://www.javaworld.com/community/node/3152">Stack Overflow after instantiating new object</a>) reminded me that the basics of the <a href="http://java.sun.com/javase/6/docs/api/java/lang/StackOverflowError.html">StackOverflowError</a> are not always understood well by people new to Java.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>A recent <a href="http://www.javaworld.com/community/">JavaWorld Community</a> forum message (<a href="http://www.javaworld.com/community/node/3152">Stack Overflow after instantiating new object</a>) reminded me that the basics of the <a href="http://java.sun.com/javase/6/docs/api/java/lang/StackOverflowError.html">StackOverflowError</a> are not always understood well by people new to Java.  Fortunately, the <a href="http://stackoverflow.com/questions/214741/what-is-a-stack-overflow-error">StackOverflowError</a> is one of the easier of the runtime errors to debug and in this blog posting I will demonstrate how easy it often is to diagnose a <a href="http://en.wikipedia.org/wiki/Stack_overflow">StackOverflowError</a>.  Note that the potential for <a href="http://support.microsoft.com/kb/145799">stack overflow is not limited to Java</a>.</p>
<p>Diagnosing the cause of a <a href="http://www.herongyang.com/jvm/stack.html">StackOverflowError</a> can be fairly straightfoward if the code has been compiled with the debug option turned on so that line numbers are available in the resulting stack trace.  In such cases, it is typically simply a matter of finding the repeating pattern of line numbers in the stack trace.  The pattern of repeating line numbers is helpful because a <a href="http://stackoverflow.com/questions/951635/how-to-handle-stackoverflowerror-in-java">StackOverflowError</a> is often caused by unterminated <a href="http://ahmadsoft.org/articles/recursion/index.html">recursion</a>.  The repeating line numbers indicate the code that is being directly or indirectly recursively called.  Note that there are <a href="http://jstevenperry.javadevelopersjournal.com/stackoverflowerror_during_jaxb_generation_of_large_schemas.htm">situations other than unbounded recursion</a> in which a stack overflow might occur, but this blog posting is limited to <code>StackOverflowError</code> caused by unbounded recursion.</p>
<p>The relationship of recursion gone bad to <code>StackOverflowError</code> is noted in the <a href="http://java.sun.com/javase/6/docs/api/java/lang/StackOverflowError.html">Javadoc description for StackOverflowError</a> that states that this <a href="http://java.sun.com/javase/6/docs/api/java/lang/Error.html">Error</a> is "Thrown when a stack overflow occurs because an application recurses too deeply."  It is significant that <code>StackOverflowError</code> ends with the word <strong>Error</strong> and is an Error (extends <a href="http://java.sun.com/javase/6/docs/api/java/lang/Error.html">java.lang.Error</a> via <a href="http://java.sun.com/javase/6/docs/api/java/lang/VirtualMachineError.html">java.lang.VirtualMachineError</a>) rather than a <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html">checked</a> or runtime <a href="http://java.sun.com/javase/6/docs/api/java/lang/Exception.html">Exception</a>.  The difference is significant.  The <code>Error</code> and <code>Exception</code> are each a specialized <a href="http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html">Throwable</a>, but their intended handling is quite different.  The <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/catchOrDeclare.html">Java Tutorial</a> points out that Errors are typically external to the Java application and thus normally cannot and should not be caught or handled by the application.</p>
<p>I will demonstrate running into <code>StackOverflowError</code> via unbounded recursion with three different examples.  The code used for these examples is contained in three classes, the first of which (and the main class) is shown next.  I list all three classes in their entirety because line numbers are significant when debugging the <code>StackOverflowError</code>.</p>
<p><strong>StackOverflowErrorDemonstrator.java</strong></p>
<p>package dustin.examples.stackoverflow;</p>
<p>import java.io.IOException;<br />import java.io.OutputStream;</p>
<p>/**<br /> * This class demonstrates different ways that a StackOverflowError might <br /> * occur.<br /> */<br />public class StackOverflowErrorDemonstrator<br />{<br />   private static final String NEW_LINE = System.getProperty("line.separator");</p>
<p>   /** Arbitrary String-based data member. */<br />   private String stringVar = "";</p>
<p>   /**<br />    * Simple accessor that will shown unintentional recursion gone bad.  Once<br />    * invoked, this method will repeatedly call itself.  Because there is no<br />    * specified termination condition to terminate the recursion, a<br />    * StackOverflowError is to be expected.<br />    *<br />    * @return String variable.<br />    */<br />   public String getStringVar()<br />   {<br />      // <br />      // WARNING:<br />      //<br />      // This is BAD!  This will recursively call itself until the stack<br />      // overflows and a StackOverflowError is thrown.  The intended line in<br />      // this case should have been:<br />      //                                  return this.stringVar;<br />      return getStringVar();<br />   }</p>
<p>   /**<br />    * Calculate factorial of the provided integer.  This method relies upon<br />    * recursion.<br />    *<br />    * @param number The number whose factorial is desired.<br />    * @return The factorial value of the provided number.<br />    */<br />   public int calculateFactorial(final int number)<br />   {<br />      // WARNING: This will end badly if a number less than zero is provided.<br />      //          A better way to do this is shown here, but commented out.<br />      //return number &lt;= 1 ? 1 : number * calculateFactorial(number-1);<br />      return number == 1 ? 1 : number * calculateFactorial(number-1);<br />   }</p>
<p>   /**<br />    * This method demonstrates how unintended recursion often leads to<br />    * StackOverflowError because no termination condition is provided for the<br />    * unintended recursion.<br />    */<br />   public void runUnintentionalRecursionExample()<br />   {<br />      final String unusedString = this.getStringVar();<br />   }</p>
<p>   /**<br />    * This method demonstrates how unintended recursion as part of a cyclic<br />    * dependency can lead to StackOverflowError if not carefully respected.<br />    */<br />   public void runUnintentionalCyclicRecusionExample()<br />   {<br />      final State newMexico = State.buildState("New Mexico", "NM", "Santa Fe");<br />      System.out.println("The newly constructed State is:");<br />      System.out.println(newMexico);<br />   }</p>
<p>   /**<br />    * Demonstrates how even intended recursion can result in a StackOverflowError<br />    * when the terminating condition of the recursive functionality is never<br />    * satisfied.<br />    */<br />   public void runIntentionalRecursiveWithDysfunctionalTermination()<br />   {<br />      final int numberForFactorial = -1;<br />      System.out.print("The factorial of " + numberForFactorial + " is: ");<br />      System.out.println(calculateFactorial(numberForFactorial));<br />   }</p>
<p>   /**<br />    * Write this class's main options to the provided OutputStream.<br />    *<br />    * @param out OutputStream to which to write this test application's options.<br />    */<br />   public static void writeOptionsToStream(final OutputStream out)<br />   {<br />      final String option1 =<br />         "1. Unintentional (no termination condition) single method recursion";<br />      final String option2 =<br />         "2. Unintentional (no termination condition) cyclic recursion";<br />      final String option3 =<br />         "3. Flawed termination recursion";<br />      try<br />      {<br />         out.write((option1 + NEW_LINE).getBytes());<br />         out.write((option2 + NEW_LINE).getBytes());<br />         out.write((option3 + NEW_LINE).getBytes());<br />      }<br />      catch (IOException ioEx)<br />      {<br />         System.err.println("(Unable to write to provided OutputStream)");<br />         System.out.println(option1);<br />         System.out.println(option2);<br />         System.out.println(option3);<br />      }<br />   }</p>
<p>   /**<br />    * Main function for running StackOverflowErrorDemonstrator.<br />    */<br />   public static void main(final String[] arguments)<br />   {<br />      if (arguments.length &lt; 1)<br />      {<br />         System.err.println(<br />            "You must provide an argument and that single argument should be");<br />         System.err.println(<br />            "one of the following options:");<br />         writeOptionsToStream(System.err);<br />         System.exit(-1);<br />      }</p>
<p>      int option = 0;<br />      try<br />      {<br />         option = Integer.valueOf(arguments[0]);<br />      }<br />      catch (NumberFormatException notNumericFormat)<br />      {<br />         System.err.println(<br />            "You entered an non-numeric (invalid) option [" + arguments[0] + "]");<br />         writeOptionsToStream(System.err);<br />         System.exit(-2);<br />      }</p>
<p>      final StackOverflowErrorDemonstrator me = new StackOverflowErrorDemonstrator();<br />      switch (option)<br />      {<br />         case 1 :<br />            me.runUnintentionalRecursionExample();<br />            break;<br />         case 2 :<br />            me.runUnintentionalCyclicRecusionExample();<br />            break;<br />         case 3 :<br />            me.runIntentionalRecursiveWithDysfunctionalTermination();<br />            break;<br />         default :<br />            System.err.println("You provided an unexpected option [" + option + "]"); <br />      }<br />   }<br />}</p>
<p>The class above demonstrates three types of unbounded recursion: accidental and completely unintended recursion, unintended recursion associated with intentionally cyclic relationships, and intended recursion with insufficient termination condition.     Each of these and their output are discussed next.</p>
<p><strong>Completely Unintended Recursion</strong></p>
<p>There can be times when recursion occurs with no intent of it whatsoever.  A common cause might be having a method accidentally call itself.  For example, it is not too difficult to get a little too careless and select an IDE's first recommendation on a return value for a "get" method that might end up being a call to that very same method!  This is in fact the example shown in the class above.  The <code>getStringVar()</code> method repeatedly calls itself until the <code>StackOverflowError</code> is encountered.  The output will appear as follows:</p>
<p>Exception in thread "main" java.lang.StackOverflowError<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.getStringVar(StackOverflowErrorDemonstrator.java:34)<br /> at </p>
<p>The stack trace shown above actually is many times longer than that which I placed above, but it is simply the same repeating pattern.  Because the pattern is repeating, it is easy to diagnose that line 34 of the class is the problem-causer.  When we look at that line, we see that it is indeed the statement <code>return getStringVar()</code> that ends up repeatedly calling itself.  In this case, we can quickly realize that the intended behavior was to instead <code>return this.stringVar;</code>.</p>
<p><strong>Unintended Recursion with Cyclic Relationships</strong></p>
<p>There are certain risks to having cyclic relationships between classes.  One of these risks is the greater likelihood of running into unintended recursion where the cyclic dependencies are continually called between objects until the stack overflows.  To demonstrate this, I use two more classes.  The <code>State</code> class and the <code>City</code> class have a cyclic relationshiop because a <code>State</code> instance has a reference to its capital <code>City</code> and a <code>City</code> has a reference to the <code>State</code> in which it is located.</p>
<p><strong>State.java</strong></p>
<p>package dustin.examples.stackoverflow;</p>
<p>/**<br /> * A class that represents a state and is intentionally part of a cyclic<br /> * relationship between City and State.<br /> */<br />public class State<br />{<br />   private static final String NEW_LINE = System.getProperty("line.separator");</p>
<p>   /** Name of the state. */<br />   private String name;</p>
<p>   /** Two-letter abbreviation for state. */<br />   private String abbreviation;</p>
<p>   /** City that is the Capital of the State. */<br />   private City capitalCity;</p>
<p>   /**<br />    * Static builder method that is the intended method for instantiation of me.<br />    *<br />    * @param newName Name of newly instantiated State.<br />    * @param newAbbreviation Two-letter abbreviation of State.<br />    * @param newCapitalCityName Name of capital city.<br />    */<br />   public static State buildState(<br />      final String newName,<br />      final String newAbbreviation,<br />      final String newCapitalCityName)<br />   {<br />      final State instance = new State(newName, newAbbreviation);<br />      instance.capitalCity = new City(newCapitalCityName, instance);<br />      return instance;<br />   }</p>
<p>   /**<br />    * Parameterized constructor accepting data to populate new instance of State.<br />    *<br />    * @param newName Name of newly instantiated State.<br />    * @param newAbbreviation Two-letter abbreviation of State.<br />    */<br />   private State(<br />      final String newName,<br />      final String newAbbreviation)<br />   {<br />      this.name = newName;<br />      this.abbreviation = newAbbreviation;<br />   }</p>
<p>   /**<br />    * Provide String representation of the State instance.<br />    *<br />    * @return My String representation.<br />    */<br />   @Override<br />   public String toString()<br />   {<br />      // WARNING: This will end badly because it calls City's toString()<br />      //          method implicitly and City's toString() method calls this<br />      //          State.toString() method.<br />      return  "StateName: " + this.name + NEW_LINE<br />            + "StateAbbreviation: " + this.abbreviation + NEW_LINE<br />            + "CapitalCity: " + this.capitalCity;<br />   }<br />}</p>
<p><strong>City.java</strong></p>
<p>package dustin.examples.stackoverflow;</p>
<p>/**<br /> * Encapsulates City information and provides example of cyclic dependency.<br /> */<br />public class City<br />{<br />   private static final String NEW_LINE = System.getProperty("line.separator");</p>
<p>   /** Name of City. */<br />   private String name;</p>
<p>   /** Name of State the city is part of. */<br />   private State state;</p>
<p>   /**<br />    * Parameterized constructor accepting parameters to populate me.<br />    *<br />    * @param newCityName Name of this newly instantiated city.<br />    * @param newState State to which this city belongs.<br />    */<br />   public City(<br />      final String newCityName,<br />      final State newState)<br />   {<br />      this.name = newCityName;<br />      this.state = newState;<br />   }</p>
<p>   /**<br />    * Provide String representation of this instance of City.<br />    *<br />    * @return My String representation.<br />    */<br />   @Override<br />   public String toString()<br />   {<br />      // WARNING: This will end badly because it calls State's toString()<br />      //          method implicitly and State's toString() method calls this<br />      //          City.toString() method.<br />      return  "City Name: " + this.name + NEW_LINE<br />            + "State: " + this.state;<br />   }<br />}</p>
<p>In my example, the <code>StackOverflowError</code> occurs when the respective <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString()">toString()</a> methods of each object try to call one another.  They do so repeatedly until they overflow the stack.  The output from running the test is shown next:</p>
<p>The newly constructed State is:<br />Exception in thread "main" java.lang.StackOverflowError<br /> at java.lang.StringBuilder.append(StringBuilder.java:119)<br /> at dustin.examples.stackoverflow.City.toString(City.java:41)<br /> at java.lang.String.valueOf(String.java:2826)<br /> at java.lang.StringBuilder.append(StringBuilder.java:115)<br /> at dustin.examples.stackoverflow.State.toString(State.java:62)<br /> at java.lang.String.valueOf(String.java:2826)<br /> at java.lang.StringBuilder.append(StringBuilder.java:115)<br /> at dustin.examples.stackoverflow.City.toString(City.java:41)<br /> at java.lang.String.valueOf(String.java:2826)<br /> at java.lang.StringBuilder.append(StringBuilder.java:115)<br /> at dustin.examples.stackoverflow.State.toString(State.java:62)<br /> at java.lang.String.valueOf(String.java:2826)<br /> at java.lang.StringBuilder.append(StringBuilder.java:115)<br /> at dustin.examples.stackoverflow.City.toString(City.java:41)<br /> at java.lang.String.valueOf(String.java:2826)<br /> at java.lang.StringBuilder.append(StringBuilder.java:115)<br /> at dustin.examples.stackoverflow.State.toString(State.java:62)<br /> at java.lang.String.valueOf(String.java:2826)<br /> at java.lang.StringBuilder.append(StringBuilder.java:115)<br /> at dustin.examples.stackoverflow.City.toString(City.java:41)<br /> at java.lang.String.valueOf(String.java:2826)</p>
<p>As with the stack trace shown in the previous example, this one actually goes on much longer than the small sample I included above.  Like that previous example, the remainder was simply repeated lines of what is shown in the above sample.  In this case, we can see repeated line numbers.  In particular, we see that line 41 of City.java and line 62 of State.java are repeat offenders.  When we look at what these lines are in these two classes, it is not surprising that it is the "return" statement in each class's respective <code>toString</code> implementation where the other class's <code>toString</code> method is implicitly invoked.</p>
<p>Once we see the repeating pattern and identify the cause as the cyclic <code>toString</code> invocations, we have several choices for fixing the situation.  An obvious and easy approach is to reference portions of the "other" object rather than relying on the other object's <code>toString</code>.  For example, we could add "get" methods to each object to return the name of the city or state and then have the <code>toString</code> implementations only call the <code>getName()</code> of the other class.  We would only need to do this for one or the other to break the cycle, but we might choose that approach for both anyway.</p>
<p><strong>Intended Recursion with Dysfunctional Termination Condition</strong></p>
<p>Even with intentional recursion, we might run into a <code>StackOverflowError</code> if our terminating condition is insufficient for all cases our code might encounter.  In the example in this blog posting, the everyday recursion example of implementing a factorial is used.  However, the terminating condition is changed just enough to lead to problems </p>
<p>The factorial of -1 is: Exception in thread "main" java.lang.StackOverflowError<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at dustin.examples.stackoverflow.StackOverflowErrorDemonstrator.calculateFactorial(StackOverflowErrorDemonstrator.java:49)<br /> at </p>
<p>Like the other two previously displayed stack traces, only a small sample of this one is shown.  The remainder of it is the same anyway.</p>
<p>This last <code>StackOverflowError</code> could have been avoided in a couple ways.  First, we could have improved the termination condition to check for a passed in number less than or equal to one to return 1.  The result of the factorial calculation might still not be correct, but at least it would not result in a <code>StackOverflowError</code>.  An even better solution might be to check the passed-in integer to ensure that it is positive and throw an <a href="http://java.sun.com/javase/6/docs/api/java/lang/IllegalArgumentException.html">IllegalArgumentException</a> if it is not.</p>
<p>Whether the appropriate recursion termination condition is enforced prior to applying recursion or as part of the recursion termination condition itself or both, the important point here is that all paths into the recursive functionality must be accounted for and terminated appropriately.  Otherwise, recursive functionality can become unbounded and result in a <code>StackOverflowError</code>.</p>
<p><strong>StackOverflowError sans Recursion</strong></p>
<p>As I mentioned earlier, a <code>StackOverflowError</code> might be encountered for reasons other than unbounded recursion.  In such situations, the fix will be something other than bounding recursion.  Solutions might include eliminating obscenely large objects allocated on the stack or increasing the <a href="http://forums.sun.com/thread.jspa?threadID=756468">default stack size</a> (<a href="http://www.javaworld.com/javaforums/showflat.php?Number=30206&amp;page=44">-Xss JVM option</a> on HotSpot JVM).  Most often, however, I have seen <code>StackOverflowError</code> associated with uncontrolled recursion and these are often easily addressed.</p>
<p><strong>Conclusion</strong></p>
<p>The <code>StackOverflowError</code> is often one of the easier errors to debug and diagnose.  Because it is commonly associated with unterminated recursion, the key to diagnosing the error is to typically look for patterns of repetitious code calls and then figure out why that series of calls never reaches a terminating condition.  The <code>StackOverflowError</code> is a runtime error by nature.  The best way to avoid it is to carefully consider one's termination conditions when using explicit recursion, be cautious when using cyclic references, and to be on the watch for accidental and completely unintended recursion.  Fortunately, if an unterminated recursive condition does creep in, it is typically relatively easy to diagnose and often not too difficult to resolve.</p>
    ]]></content>
  </entry>
  <entry>
    <title>2009 JavaOne: Still Effective Java</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3150" />
    <id>http://www.javaworld.com/community/node/3150</id>
    <published>2009-07-03T11:27:00-04:00</published>
    <updated>2009-07-04T20:56:25-04:00</updated>
    <author>
      <name>dmarx</name>
    </author>
    <category term="Dustin" />
    <category term="Java (General)" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>As evidenced by <a href="http://marxsoftware.blogspot.com/search?q=effective+java">several previous blog posts</a> (including <a href="http://marxsoftware.blogspot.com/2008/04/what-makes-good-technical-book.html">What Makes a Great Technical Book?</a>) I am a big fan of the book <a href="http://java.sun.com/docs/books/effective/">Effective Java</a>.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>As evidenced by <a href="http://marxsoftware.blogspot.com/search?q=effective+java">several previous blog posts</a> (including <a href="http://marxsoftware.blogspot.com/2008/04/what-makes-good-technical-book.html">What Makes a Great Technical Book?</a>) I am a big fan of the book <a href="http://java.sun.com/docs/books/effective/">Effective Java</a>.  It therefore is not surprising that one the first 2009 <a href="http://java.sun.com/javaone/">JavaOne</a> presentations that I looked at when the slides were made available was <a href="http://en.wordpress.com/tag/joshua-bloch/">Joshua Bloch</a>'s <a href="http://developers.sun.com/learning/javaoneonline/sessions/2009/pdf/TS-5217.pdf">Effective Java: Still Effective, After All These Years</a> (<a href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-5217&amp;yr=2009&amp;track=javase">TS-5217</a>).</p>
<p>This presentation begins by comparing the <a href="http://marxsoftware.blogspot.com/2008/04/effective-java-second-edition.html">Second Edition</a> of <a href="http://www.pearsonhighered.com/educator/academic/product/0,3110,0137150024,00.html">Effective Java</a> to the First Edition in terms of number of items covered in each edition.  The major <a href="http://java.dzone.com/articles/effective-java-an-interview-wi">new topics</a> (including a completely overhauled chapter on <a href="http://www.cs.gmu.edu/~pammann/619/ppt/Bloch10.ppt">concurrency</a>) are also highlighted.  I like that the Second Edition of <a href="http://www.javaspecialists.eu/archive/Issue163.html">the book</a> contains a table at the end of the book that provides a mapping of items in the First Edition to items in the Second Edition.</p>
<p><strong>Focus of Presentation</strong></p>
<p>The <em>Effective Java: Still Effective, After All These Years</em> presentation focuses on the new items in the Second Edition: <a href="http://www.cs.gmu.edu/~pammann/619/ppt/Bloch5.ppt">Generics</a>, <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html">Enum Types</a>, <a href="http://www.onjava.com/pub/a/onjava/excerpt/javaadn_chap5/index.html">Variable Arguments</a>, <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html">Concurrency</a>, and <a href="http://java.sun.com/javase/6/docs/technotes/guides/serialization/index.html">Serialization</a> (the "new" focus here is the <a href="http://stackoverflow.com/questions/702357/what-is-the-serialization-proxy-pattern">Serialization Proxy Pattern</a>).  It's no surprise that the content of these slides is similar to select content from the book.</p>
<p><strong>Generics</strong></p>
<p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=222021">Bloch</a> uses several slides of this presentation to cover use of <a href="http://www.devarticles.com/c/a/Java/Wildcards-and-Generic-Methods-in-Java/">wildcards with generics</a> and covers the <a href="http://java.sun.com/docs/books/effective/generics.pdf">acronym he introduced</a> in the second edition: PECS -&gt; Producer Extends, Consumer Super.  This mnemonic is a variation of the <a href="http://codeidol.com/java/javagenerics/Subtyping-and-Wildcards/The-Get-and-Put-Principle/">Get and Put Principle</a> that <a href="http://naftalin.info/maurice/professional/">Naftalin</a> and <a href="http://homepages.inf.ed.ac.uk/wadler/">Wadler</a> discuss in <a href="http://oreilly.com/catalog/9780596527754/">Java Generics and Collections</a> (one of the deepest Java books I have read).</p>
<p>Whether it is PECS or "Get and Put," the principle is the same: use the <code>extends</code> keyword with generics wildcards when retrieving data (get) from a source data structure (producer extends) or use the <code>super</code> keyword with generics wildcards when inserting data (put) into a data structure (consumer super).  As he does in the book, Bloch points out in the slides that these generics wildcards should only be used for method arguments and not for method return values.  Also, it is worth noting that it is nonsensical to have a single method argument use both <code>extends</code> and <code>super</code>.</p>
<p><strong>Enums</strong></p>
<p>Bloch covers some advantages of enums in this presentation.  I already love the Java enum and don't need any convincing in this case.  Compared to generics, enums are very simple to understand and apply.  In fact, my biggest problem with enums is that I'm often tempted to stretch them past what they are intended for.  I didn't see it covered in this presentation, but one of the things Bloch points out in the Second Edition of <em>Effective Java</em> that has really grown on me is the idea of an <a href="http://stackoverflow.com/questions/427902/java-enum-singleton">enum-based singleton</a>.</p>
<p><strong>Variable Arguments</strong></p>
<p>Throughout <em>Effective Java</em>, Bloch repeatedly mentions that many of the covered items are "effective" because they move the reporting of problems to as early as possible in the process.  Specifically, many of the best practices in his book lead to issues being discovered at compile time rather than at runtime.  In the second edition of the book and in this presentation, Bloch points out that using variable arguments recklessly can lead to runtime problems.  Specifically, he recommends always explicitly specifying the first argument of a variable arguments list as a single argument followed by varargs syntax for the remaining potential parameters of that same type when at least one is required.  This prevents the runtime error if a method is called without any arguments.  It will instead be discovered at compile time.  In other words, the compiler can enforce the requirement of at least one argument being provided.</p>
<p><strong>Concurrency / Threading</strong></p>
<p><a href="http://java.sun.com/j2se/1.5.0/">J2SE 5</a> saw dramatic changes to Java's <a href="http://java.sun.com/developer/technicalArticles/J2SE/concurrency/">concurrency support</a> and the changes to the second edition of <em>Effective Java</em> reflect that.  Several slides in this presentation focus on concurrency.  This is the portion of the presentation where I think the liner notes from Bloch's verbal presentation would be especially helpful.  </p>
<p><strong>Serialization</strong></p>
<p>Bloch discusses the Serialization Proxy Pattern as a better way of dealing with some common limitations associated with <a href="http://java.sys-con.com/node/36635">serialization in Java</a>.  He uses code to demonstrate the pattern in practice and also notes that this approach will not always be appropriate.</p>
<p><strong>Some of My Favorite Items in Second Edition</strong></p>
<p>Two of the items that the Second Edition of <em>Effective Java</em> newly covers that helped me justify purchasing a new edition do not seem to receive focus in this presentation, but they are covered in the excerpt available from the book itself: <a href="http://www.sun.com/books/documents/effective_java_ch02.pdf">Chapter 2: Creating and Destroying Objects</a>.  I use the Item 2 recommendation (Builder implementation rather than telescoping constructor) and the recommendation at the very end of Item 3 (enum implementation of Singleton) relatively frequently.  I also use static factories in many cases, but that was the first item in the First Edition as well.</p>
<p><strong>Benefiting from this Presentation</strong></p>
<p>Different Java developers are likely to benefit from this presentation in different ways.  For those of us who own (or have borrowed) the Second Edition and have read it, most of this material is not new.  However, it is still useful to see it again and can sometimes be helpful to see it in different form (slides rather than book pages).</p>
<p>For those who own the Second Edition, but have not read it, this presentation gives a taste of what's available there and might provide motivation to invest time in reading.  For those who own the First Edition and are thinking about purchasing the Second Edition, this presentation provides a nice taste of the types of things newly covered in the Second Edition, though a presentation of this length could not adequately cover all the concepts and ideas introduced with the Second Edition of <em>Effective Java</em>.</p>
<p><strong>Other Coverage</strong></p>
<p>There are other resources out there that review this presentation or that are related to this presentation.  They are too numerous to list them all here, but I do list a few:</p>
<p>&#8853; <a href="http://thedevelopercorner.blogspot.com/2009/06/javaone-2009-effective-java.html">JavaOne 2009: Effective Java</a></p>
<p>&#8853; <a href="http://www.sun.com/books/documents/effective_java_ch02.pdf">Effective Java, Second Edition, Chapter 2</a></p>
<p>&#8853; <a href="http://java.sun.com/docs/books/effective/generics.pdf">Effective Java, Second Edition, Chapter 5</a></p>
<p>&#8853; <a href="http://www.infoq.com/articles/bloch-effective-java-2e">Book Excerpt and Interview: Effective Java, Second Edition</a></p>
<p>&#8853; <a href="http://www.javaspecialists.eu/archive/Issue163.html">Book Review: Effective Java Second Edition</a></p>
<p>&#8853; <a href="http://blog.segersconsulting.com/?p=592">Effective Java -- Still Effective?</a></p>
<p>&#8853; <a href="http://www.flickr.com/photos/skrb/3631315290/">Photograph of Presentation</a></p>
    ]]></content>
  </entry>
  <entry>
    <title>Android becoming ever more unmoored from Java</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3146" />
    <id>http://www.javaworld.com/community/node/3146</id>
    <published>2009-07-02T11:36:43-04:00</published>
    <updated>2009-07-02T11:36:43-04:00</updated>
    <author>
      <name>Josh Fruhlinger</name>
    </author>
    <category term="Android" />
    <category term="Google" />
    <category term="Java ME" />
    <category term="JNI" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>Android has always held a weirdly ambiguous position in regards to Sun's official Java.  On the one hand, applications written for Android are written in Java code, and so the platform's popularity can only help reinforce Java's popularity among developers.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Android has always held a weirdly ambiguous position in regards to Sun's official Java.  On the one hand, applications written for Android are written in Java code, and so the platform's popularity can only help reinforce Java's popularity among developers.  On the other, Android's VM is based on Apache's non-Sun-certified Harmony, which means it doesn't carry the Java brand (and the lucrative licensing fees that go with it); in addition, because Harmony is a tweaked Java SE implementation, code written for Android doesn't match up with the Java ME standard that Sun would like to see be the default for mobile device development.  It's no wonder Sun's official Java ME bloggers <a href="http://blogs.sun.com/hinkmond/entry/google_s_android_no_match" target="_blank">tend to slag on it</a>.</p>

<p>Because of all this, Android isn't that tied into Java as an aspect to its identity, despite the buzz about its appeal to Java programmers when it was first announced; after all, it's not really so much a "Java phone" as it is a Linux phone.  That's why Google can take steps like the one announced last week, which will open up Android to <a href="http://arstechnica.com/open-source/news/2009/06/android-goes-beyond-java-gains-native-cc-dev-kit.ars" target="_blank">C/C++ code running on the phone's processor</a>.  Now, this is admittedly just based on the JNI functionality already in place in most Java SE implementations, but it could be the start of a trend.  It's also worth noting that Google is releasing a <a href="http://www.infoq.com/news/2009/06/android-scripting" target="_blank">scripting environment</a> that will allow developers and even end users to run Python and Lua code on Android. It also seems that other VM languages are coming; IBM's developerWorks has a tutorial on running <a href="http://www.ibm.com/developerworks/opensource/library/os-eclipse-scala/index.html" target="_blank">Scala apps on your Android phone</a>.</p>

<p>It's possible that Android would have taken this road eventually anyway -- after all, the appeal of a Linux-based system is its flexibility.  But I can't help but think that Android was a lost opportunity for Java, and is becoming more so by the day.</p>    ]]></content>
  </entry>
  <entry>
    <title>2009 JavaOne: Project Coin</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3141" />
    <id>http://www.javaworld.com/community/node/3141</id>
    <published>2009-07-02T00:58:00-04:00</published>
    <updated>2009-07-04T20:56:26-04:00</updated>
    <author>
      <name>dmarx</name>
    </author>
    <category term="Dustin" />
    <category term="Java SE 7" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>I have enjoyed reading some of the 2009 <a href="http://java.sun.com/javaone/">JavaOne</a> presentations since they have been <a href="http://developers.sun.com/learning/javaoneonline/">made available online</a>.  One of the presentations I was most interested to read was <a href="http://blogs.sun.com/darcy/">Joseph Darcy</a>'s <a href="http://blogs.sun.com/darcy/entry/javaone_2009_project_coin_slides">Small Language Changes in JDK Release 7: Project Coin</a> (<a href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-4060&amp;yr=2009&amp;track=javase">TS-4060</a>).</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>I have enjoyed reading some of the 2009 <a href="http://java.sun.com/javaone/">JavaOne</a> presentations since they have been <a href="http://developers.sun.com/learning/javaoneonline/">made available online</a>.  One of the presentations I was most interested to read was <a href="http://blogs.sun.com/darcy/">Joseph Darcy</a>'s <a href="http://blogs.sun.com/darcy/entry/javaone_2009_project_coin_slides">Small Language Changes in JDK Release 7: Project Coin</a> (<a href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-4060&amp;yr=2009&amp;track=javase">TS-4060</a>).  I have <a href="http://marxsoftware.blogspot.com/2009/02/small-java-7-language-changes.html">blogged on Project Coin previously</a>, but am using this blog post to summarize some of the things I found most interesting about this JavaOne presentation.</p>
<p><strong>Improved Dynamic Language Support on the JVM</strong></p>
<p>Scripting languages on the JVM have begun to really gain traction in terms of popularity and use.  One of Darcy's first slides mentions <a href="http://jcp.org/en/jsr/detail?id=292">JSR 292</a> ("<a href="http://www.artima.com/lejava/articles/dynamic_languages.html">Supporting Dynamically Typed Languages on the Java Platform</a>"), which proposes a new bytecode called <a href="http://blogs.sun.com/gbracha/resource/JAOO2005.pdf">invokedynamic</a> and additional support for easier implementation of dynamic languages on the <a href="http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html">Java Virtual Machine</a>.</p>
<p><strong>Improved Modularity</strong></p>
<p>The presentation also has a slide focusing on the desired <a href="http://blogs.sun.com/mr/entry/modular_java_platform">improved modularity</a> expected for Java SE 7.  This was a popular topic at 2009 JavaOne as evidenced by the presentations on it (such as the one on <a href="http://openjdk.java.net/projects/jigsaw/">Project Jigsaw</a>) and by the Mark Reinhold quote "<a href="http://www.nofluffjuststuff.com/blog/alex_miller/2009/06/javaone_jigsaw_and_java_modularity.html">The classpath is dead</a>."  This actually is a very significant change, but it is briefly covered in this presentation.</p>
<p><strong>The Elvis Operator</strong></p>
<p>One of the "small features" covered in this presentation is the so-called "<a href="http://groovy.codehaus.org/Operators#Operators-ElvisOperator(%3F%3A)">Elvis operator</a>," a more concise version of the ternary operator.  I find myself missing some of the features of <a href="http://groovy.codehaus.org/">Groovy</a> when using traditional Java and this would be one operator that I could use in both languages if it was added.  The "Elvis" operator is handy for specifying a default value that can be used when the evaluated expression is null.  Like Groovy's <a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator(%3F.)">safe navigation operator</a>, it is a concise way to specify how to avoid unnecessary nulls.  I have <a href="http://marxsoftware.blogspot.com/2009/04/effective-java-nullpointerexception.html">blogged previously</a> about how I like to avoid the <a href="http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html">NullPointerException</a>.</p>
<p><strong>Switch on String in Java</strong></p>
<p>Joe Darcy is a submitter of the proposal to add the ability to <a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html">switch</a> on <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html">String</a> in Java.  I have <a href="http://marxsoftware.blogspot.com/2007/11/java-and-actionscript-switch-case-and.html">blogged previously</a> regarding this versus the ability to switch on String in <a href="http://www.adobe.com/devnet/actionscript/">ActionScript</a>.  Although I find myself missing the ability to switch on a String in Java less now with the fantastic <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html">Enum</a> and polymorphism, there are still situations I run into (often when using third-party libraries) where it would be nice to switch on a String.</p>
<p><strong>Better Exception Handling</strong></p>
<p>A slide in this presentation covers the proposed improvements to exception handling to allow a single catch statement to catch multiple explicitly specified exceptions.  This can be much nicer than repeating code in each individual exception catch block.</p>
<p><strong>Other Small Language Features Being Considered</strong></p>
<p>There are a few other potential new Java SE 7 language features covered in the slides of this presentation.  They include <a href="http://tech.puredanger.com/java7/#resourceblock">automatic resource management</a>, <a href="http://tech.puredanger.com/java7/#typeinference">type inference</a> ("Diamond"), and <a href="http://jroller.com/scolebourne/entry/java_7_list_and_map">list and map literals</a>.</p>
<p><strong>On Selecting What To Include</strong></p>
<p>Although it is interesting to see which small language change proposals are being seriously considered, perhaps the most interesting aspect of this presentation for me is the coverage of the many things that must be considered when weighing which options to add.  Darcy talks in this presentation about the importance of thinking in the big perspective rather than with limited view of what would be nice.  He has a slide titled "Greed is Not Always Good" and includes perhaps the most important point to keep in mind when thinking about what one would like in Java:</p>
<p>"Default response is to keep the language as-is.  Burden is on the proposer to convince that a change gets in; burden is not to convince to keep a change out."</p>
<p>I also enjoyed Darcy's slides covering all the work involved in a language change above and beyond the implementation of the feature itself.  He has an overview slide in which he demonstrates the many related artifacts that must be updated such as the <a href="http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html">Java Language Specification</a> and updating the <a href="http://java.sun.com/javase/6/docs/api/">Javadoc output</a>.  Darcy devotes several slides to each of the artifacts that need updating and then really drives the point home by using the introduction of the enum as an example.  I love the enum, but it is obvious that it needed to be really desired to justify the effort.</p>
<p><strong>What's Not Going to be in Java SE 7</strong></p>
<p>After making a compelling case for adequately comparing the value and benefit of a particular new language feature to the cost of its introduction, Darcy has a slide in which he highlights in red some popular new features that will <a href="http://marxsoftware.blogspot.com/2008/12/most-missed-java-se-7-features.html">NOT be going into Java SE 7</a>.  These are contrasted on the same slide with features first implemented in <a href="http://java.sun.com/j2se/1.5.0/">J2SE 5</a>.  What interests me about this slide is to see where features punted from Java SE 7 (<a href="http://www.javac.info/">closures</a>, <a href="http://gafter.blogspot.com/2006/11/reified-generics-for-java.html">reification</a> [<a href="http://tech.puredanger.com/java7/#reified">my favorite</a>], and <a href="http://tech.puredanger.com/java7/#property">properties</a>) rank in terms of effort against features that were implemented with J2SE 5 (<a href="http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html">enums</a>, <a href="http://java.sun.com/developer/JDCTechTips/2005/tt0405.html#1">autoboxing</a>/unboxing, <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html">annotation types</a>, and <a href="http://java.sun.com/docs/books/tutorial/java/generics/index.html">generics</a>).</p>
<p><strong>Keeping Up with Project Coin and Other Java SE 7 Developments</strong></p>
<p>Because Java SE 7 is still clearly a work in progress, it is not surprising that one slide in the presentation warns about forward-looking statements in the presentation.  We should all be aware that any of these mentioned changes may not actually end up in Java SE 7.  I have found <a href="http://tech.puredanger.com/">Alex Miller</a>'s <a href="http://tech.puredanger.com/java7/">Java 7 site</a> to be my favorite one-stop shop for the latest news on Java SE 7 developments.  He apparently scours the web and blogosphere for articles that he links there and writes his own blog postings and articles as well.  He currently has the status of inclusion of many proposed features listed on his page ("YES" for still planned for Java SE 7, "NO" for explicitly punted from Java SE 7, or other status if not known for certain).</p>
<p>Other useful sources of information include <a href="http://blogs.sun.com/darcy/">Joseph D. Darcy's Weblog</a>, the <a href="http://openjdk.java.net/projects/coin/">Project Coin</a> web page, <a href="http://blogs.sun.com/dannycoward/">Danny Coward's Weblog</a>, <a href="http://blogs.sun.com/mr/">Mark Reinhold's Blog</a>, <a href="http://gafter.blogspot.com/">Neal Gafter's Blog</a>, and <a href="http://www.jroller.com/scolebourne/">Stephen Colebourne's Weblog</a>.</p>
    ]]></content>
  </entry>
  <entry>
    <title>Euler was groovy too</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3140" />
    <id>http://www.javaworld.com/community/node/3140</id>
    <published>2009-07-01T15:03:18-04:00</published>
    <updated>2009-07-01T15:56:20-04:00</updated>
    <author>
      <name>Andrew Glover</name>
    </author>
    <category term="Andy" />
    <category term="Dynamic Languages" />
    <category term="groovy" />
    <category term="java" />
    <category term="project euler" />
    <category term="Software Development" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>
I recently stumbled across <a href="http://projecteuler.net">Project Euler</a>, which is a hip website containing quite a few different math challenges. The idea being that people can attempt to solve any particular challenge which ever way they can (that is, in any language and with any algorithm) &#8212; the site doesn&#8217;t provide answers either &#8212; you must create an account and submit your answer. Project Euler will then check your answer and issue a response &#8212; correct or incorrect.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
I recently stumbled across <a href="http://projecteuler.net">Project Euler</a>, which is a hip website containing quite a few different math challenges. The idea being that people can attempt to solve any particular challenge which ever way they can (that is, in any language and with any algorithm) &#8212; the site doesn&#8217;t provide answers either &#8212; you must create an account and submit your answer. Project Euler will then check your answer and issue a response &#8212; correct or incorrect. If it&#8217;s your bag and you Google the project, you&#8217;ll find some interesting posts solving various problems in various languages ranging from F# to Scala to C (and everything in between). What&#8217;s also interesting is that each post for a problem usually is different in some way or another, which of course provides some interesting learning opportunities.
</p>
<p>
<a href="http://projecteuler.net/index.php?section=problems&amp;id=1">Problem 1</a> entails figuring out the sum of numbers divisible by 3 and 5:
</p>
<p>
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.<br />
Find the sum of all the multiples of 3 or 5 below 1000.
</p>
<p>
I thought it would be interesting to see if I could solve this in <a href="http://groovy.codehaus.org">Groovy</a> as the solution clearly deals with iterating over a series of numbers &#8212; and as everyone who has played with <a href="http://thediscoblog.com/category/dynamic-languages/groovy/">Groovy</a> (or some other dynamic language for that matter) knows, <a href="http://thediscoblog.com/2008/11/27/ranges-in-groovy-are-hip/">iteration is a blast</a>, baby!
</p>
<p>
Accordingly, my first pass yielded the following code: </p>
<p><div class="codeblock"><code>def sum = 0<br />(1..&amp;lt;1000).each{<br /> if((it % 5 == 0) || (it % 3 == 0)){<br />&nbsp;&nbsp; sum += it<br /> }<br />}<br />assert sum == /* do it yourself, baby! */</code></div>
</p>
<p>Note that I&#8217;m using Groovy&#8217;s <a href="http://groovy.codehaus.org/Collections">exclusive range feature</a> to easily iterate over all numbers less than 1000. I then proceed to use Groovy&#8217;s <code>it</code> variable, which represents the current value in the iteration (i.e. 1, 2, 3, etc) and test the instance with Java&#8217;s <a href="http://www.cafeaulait.org/course/week2/15.html">modulo operator</a> (that is, modulo returns the remainder of division &#8212; 10 modulo 5 is 0, but 11 modulo 5 is 1). If there is a match, I add it to the <code>sum</code> variable. This is programming 101 and brought me back to the Age of Aquarius, baby!!
</p>
<p>
That was easy enough; however, I wanted to see if I could do away with the <code>sum</code> variable by using one of Groovy&#8217;s many hip magic methods <a href="http://groovy.codehaus.org/JN1015-Collections">attached to collections</a>. Thus, my second attempt leverages Groovy&#8217;s <code>findAll</code> method, which permits putting a condition in the resulting <a href="http://thediscoblog.com/2009/02/09/leveraging-closures/">closure</a>, which then returns a collection meeting that criteria. Accordingly, with the returned collection of numbers meeting my criteria (that is, any number that is divisible by 5 or 3), I then have to issue the <code>sum</code> method like so:</p>
<p><div class="codeblock"><code>def val = (1..&amp;lt;1000).findAll{(it % 5 == 0) || (it % 3 == 0)}<br />assert val.sum() == /* you gotta figure it out yourself, man! */</code></div>
</p>
<p>Groovy&#8217;s <code>sum</code> method is straight forward &#8212; it takes all the values in a collection (presumably <a href="http://www.ibm.com/developerworks/java/library/j-pg10255.html">add-able</a>) and adds them up! </p>
<p>
Admittedly, the second example is a bit harder to read (at first glance, that is) but it sure is a bit more aesthetic than the first brute force bogue example, isn&#8217;t it?</p>
<p>You can now follow <a href="http://twitter.com/thediscoblog">The Disco Blog on Twitter</a>, baby!</p>
    ]]></content>
  </entry>
  <entry>
    <title>DoJ taking an interest in Java licensing?</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3134" />
    <id>http://www.javaworld.com/community/node/3134</id>
    <published>2009-06-30T03:29:35-04:00</published>
    <updated>2009-06-30T03:29:35-04:00</updated>
    <author>
      <name>Josh Fruhlinger</name>
    </author>
    <category term="Apache Foundation" />
    <category term="JCP" />
    <category term="merger" />
    <category term="Oracle" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>We've been talking all this time about the Sun-Oracle merger as if it's a done deal, but the US government has the right and the responsibility to examine proposed combinations to make sure they don't violate anti-trust law, and the Obama Administration is rumored to be stricter on this point than the Bush Administration was. Thus, it was not entirely unexpected that Department of Justice <a href="http://www.reuters.com/article/americasDealsNews/idUSTRE55P6N520090626" target="_blank">put the brakes on the transaction last week</a>.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>We've been talking all this time about the Sun-Oracle merger as if it's a done deal, but the US government has the right and the responsibility to examine proposed combinations to make sure they don't violate anti-trust law, and the Obama Administration is rumored to be stricter on this point than the Bush Administration was. Thus, it was not entirely unexpected that Department of Justice <a href="http://www.reuters.com/article/americasDealsNews/idUSTRE55P6N520090626" target="_blank">put the brakes on the transaction last week</a>.  This does not by any means indicate that the merger won't go through, but it does mean that the administration isn't willing to fast-track the deal, and wants to take a closer look at the implications.</p>

<p>What's interesting from our perspective is exactly what the DoJ was keen to gather more information about.  According to one of Oracle's attorneys, "All that's left is one narrow issue about the way rights to Java are licensed that is never going to get in the way of the deal."  Despite the bravado contained in the second half of that sentence, it's intriguing to say the least that the US government is so concerned about Java licensing.  Stephen Colbourne thinks that the feds might be interested in the whole <a href="http://www.jroller.com/scolebourne/entry/no_java_7_us_doj" target="_blank">Sun-Apache dispute</a>.  While it's certainly possible, and I do think this is an important issue, it's also a fairly obscure one that even the Java community at large seems largely ignorant about.  It may be that the DoJ's concerns are broader, that they're worried about a Oracle being in charge of the JCP, which will determine the fate of products being put out by many of Oracle's competitors.  An antitrust lawyer <a href="http://74.125.77.132/search?q=cache:KXlTzRGrUpoJ:online.wsj.com/article/SB124606768745364111.html+oracle+sun+doj+probe&cd=3&hl=en&ct=clnk&gl=uk&client=firefox-a" target="_blank">quoted by the <em>Wall Street Journal</em></a> notes that "Often in these cases, the acquirer agrees to certain conditions or to divest some assets"; could Oracle be required to spin off the JCP as an independent foundation?  Either way, it's intriguing that <em>someone</em> in the federal bureaucracy knows how important software licensing is.</p>    ]]></content>
  </entry>
  <entry>
    <title>Writing Code Is Much Like Writing Prose</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3133" />
    <id>http://www.javaworld.com/community/node/3133</id>
    <published>2009-06-30T01:52:00-04:00</published>
    <updated>2009-07-04T20:56:26-04:00</updated>
    <author>
      <name>dmarx</name>
    </author>
    <category term="Dustin" />
    <category term="General Development" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>There are many similarities when comparing the writing of code to the writing of prose.  Because of this, we should be able to learn from doing each of these and apply things learned from one to the other.</p>
<p><strong>The Absolutes</strong></p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>There are many similarities when comparing the writing of code to the writing of prose.  Because of this, we should be able to learn from doing each of these and apply things learned from one to the other.</p>
<p><strong>The Absolutes</strong></p>
<p>In writing code and in writing prose, there are a few things that are either absolute or approach very nearly the status of absolute.  This is especially true for programming languages where syntactic and semantic rules must be followed for the code to be compiled and/or interpreted correctly.  Even when a programming language supports certain generally frowned-upon features, some of these features are avoided to such a large degree that they almost appear absolute.  For example, direct use of "goto" is generally frowned upon and is rarely seen in most code bases.  However, less obvious versions of this (such as <code>break</code> and <code>continue</code> in Java) do seem to be less strictly avoided.</p>
<p>Although it is less strictly enforced in writing prose, there still is significant pressure to conform to certain absolutes even in writing prose.  For example, it is generally assumed that most professional prose will include sentences that begin with capital letters and end with periods.  Similarly, proper names are almost always capitalized and correct spelling and reasonable grammar are also expected.  The degree of enforcement for such things in prose often depends on the media.  Professional papers and articles typically are the most enforced with the author and professional editors investing significant effort into polishing the prose.  On the opposite end of the spectrum are e-mail messages, <a href="http://www.blogger.com/home">blogs</a>, and <a href="http://twitter.com/">Twitter</a> messages, which seem to have less enforced absolutes.</p>
<p><strong>The Frowned-Upon</strong></p>
<p>Although there are a small number of absolutes or near-absolutes as just discussed, code development and prose writing seem to have many more things that are not absolutely avoided but seem to be strongly discouraged.  However, these things tend to creep in despite their negative reputations because they do offer some advantages.  Usually the advantages these items offer are ease for the writer at the expense of later reader or maintainer having more difficult prose or code. </p>
<p>Many developers realize problems associated with using so-called "<a href="http://en.wikipedia.org/wiki/Magic_number_(programming)">magic numbers</a>."  However, they still seem to crop up.  Often they are put in place "temporarily" and then forgotten or limited schedules prevent replacing them with a constant.  These "magic numbers" are quick and easy to use when doing initial development, but can lead to a maintenance nightmare.  Global variables offer a similar trade-off of easy early development at the expense of maintainability, robustness, and scalability.</p>
<p>Prose authoring has similar frowned-upon, but still often used, features.  For example, it is often said that sentences should not end with prepositions.  Similarly, it is often said that strong, active voice should be used.  The tense of the writing should also be consistent.  These are all things that are recommended because they do offer recognized benefits, but they are also easy to ignore or cheat on a bit when it is not deemed worth the time or effort to satisfy all of them all of the time.</p>
<p><strong>The Standards</strong></p>
<p>Since nearly the beginning of software development, developers have seemed to want to create and adhere to coding standards and conventions.  Of course, we also seem to have been resistant to other peoples’ ideas of standards and conventions for nearly as long.  The reason most of us are willing to give up some "creative freedom" and adhere to standards and conventions is that we have learned that code is more readable and maintainable (especially by others) when we adhere to a minimum set of conventions.</p>
<p>Prose can benefit from the same benefits of standardization and convention.  There are books such as <a href="http://www.bartleby.com/141/">Elements of Style</a> and <a href="http://www.chicagomanualofstyle.org/home.html">Chicago Manual of Style</a> devoted to prose style.  Most of the arguments in favor of these prose writing style conventions are the same arguments used in favor of coding conventions: easier to read and maintain and consistency to benefit different readers and authors/developers.</p>
<p>One style issue is very similar between prose writing and code development.  The subject of spaces can be surprisingly controversial in both arenas.  In software development, most developers seem to agree that the optimal number of spaces for indentation is between 2 and 4 spaces.  However, trying to narrow down which of these is best (2 spaces or 3 spaces or 4 spaces) is significantly more difficult.</p>
<p>There has been a <a href="http://desktoppub.about.com/cs/typespacing/a/onetwospaces.htm">controversy in the prose writing world</a> regarding how many spaces should follow a period that ends one sentence before the first letter of the next sentence.  I grew up thinking that two spaces was the expected number of spaces between the end of one sentence and the beginning of the next sentence.  However, I was recently informed by a prose reviewer and editor that a single space is now preferred.  I wondered if this was a web browser-inspired shift, but there seems to be evidence that this shift started even before the widespread adoption of HTML.</p>
<p><strong>Conciseness</strong></p>
<p>There seem to be differences of opinion on whether prose should be concise or verbose.  To some extent, this depends on the subject of the prose.  I prefer technical prose to be as concise as possible while still remaining thorough.  This is especially true of technical references.  However, with novels, extra verbosity can sometimes be nice to explain the story and character development.  This can even go too far, for my taste, as evidenced by <a href="http://en.wikipedia.org/wiki/Moby-Dick">Moby Dick</a>.</p>
<p>I have found that even in software development there is a wide diversity of opinion about conciseness of code.  The longer I work in the industry, the more I value conciseness.  However, I know many Java developers who don’t like the same degree of conciseness that I like.  An example of this is the <a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op2.html">Java ternary operator</a>.  This operator has really grown on me, but I still know many Java developers who do not care for it at all.  Although many developers are migrating to programming languages that emphasize and value conciseness, there are limits to how concise we want to be.  After all, none of us are probably too excited to write and maintain production code that can be sneakily squeezed into a single line.</p>
<p><strong>Refactoring</strong></p>
<p>"Refactoring" is a popular term in software development, but it does have its equivalent in prose writing.  In my case, I find that when I revisit my own articles, I continually "refactor" the text to make it flow better, to reduce unnecessary repetition, and to make it generally more concise.  The editors of formal articles often do this to an even greater degree.  In fact, the editors’ reviews often remind me of how developers are eager to change others’ peoples’ code to match their own preferences.  Some of the "refactorings" I see in both development and in article editing have marginal value.  However, I think most of us can agree that some "refactoring" or editing is useful and recommended for writing code or for writing prose.</p>
<p>When the editors and reviewers at <a href="http://www.oracle.com/technology/index.html">Oracle Technology Network</a> recommended cutting my original draft of the <a href="http://www.oracle.com/technology/pub/articles/marx-jpa.html">Basic JPA Best Practices</a> article to less than half its original draft size, it took some effort to "refactor" that article to that point.  Although some minor details and some explanatory text were removed in the process, most of the substance was retained even though the final article had half as many words as my original draft.  It was not trivial trimming that draft down without losing too much substantial content, but the effort the reviewers, editors and I invested is reflected in the improvements.  That article still weighs in around 11 pages, but it is leaner, tighter, and more optimized than my original draft.  That sounds awfully similar to the benefits of code refactoring.  The process really was like refactoring because it was more than just removing words; it involved changing words and changing sentence structure and paragraph structure.</p>
<p>I don’t spend much time reviewing my blog posts at the time of their writing.  I think this is common among blogs, though some are exceptions.  Because of this, most of us expect blog posts to be rougher than formal articles.  There are definitely different expectations for different forms of writing.  Similarly in code, prototypes and demonstration code can often be a little "rougher around the edges" than highly reviewed and refactored production code.</p>
<p><strong>More Knowledge Means More Expressiveness</strong></p>
<p>When writing prose, one of the most useful techniques for writing concise but thorough prose is to know and carefully use the appropriate words and phrases.  Words have different nuances and these nuances can be used to provide more expressiveness with the same number of words.  In code, we see the same thing.  There is often more than one way to get the job done, but thorough understanding of the language’s features and provided class libraries allows us to select the most appropriate language feature or class that provides the exact nuanced solution appropriate to the problem at hand.</p>
<p>When writing prose, it is common to use well-known idioms and phrases to imply much more than the few words would normally imply.  For example, "a picture is worth a thousand words" consists of only seven words but implies much more than what we might say with only seven words.  Some assumed knowledge is required (readers must be familiar with the idiom) to make this work.  In code, we often use design patterns and other common phrases to succinctly describe much larger ideas that otherwise would require much more description.</p>
<p><strong>The Value of Review</strong></p>
<p>I have found that both code and prose that I write benefit when reviewed by someone else.  When I write my own code or prose, I know what I am trying to say and it all makes sense.   Reviewers of articles and reviewers of code can ask questions about what is intended and provide feedback that makes the code or article more generally appealing.  Sometimes we’re too close to the product for our own good and the reviewer can help us to see things that we don’t see.</p>
<p><strong>"Readable" is in the Eye of the Beholder</strong></p>
<p>To some degree, what is "readable" depends on the person doing the reading.  This applies to both prose and code.  Readers (whether reading prose or someone’s code) have their own preferences.  Just as we all like different prose authors’ writing, it is not surprising that we each find different styles of code easier or more difficult to read.  For example, I have an easier time reading code written by people who have similar tastes and preferences to mine.  For this reason, I don’t think we’ll ever see a single programming language or framework that everyone uses.   There is just too wide of a spectrum of differences of opinion for any one language or framework to appeal to everyone.  This is also an important observation to realize when writing code or prose.  You can try to appeal to the widest set possible, but no matter what you do there will probably be at least a small group of people who don’t like it.</p>
<p><strong>Conclusion</strong></p>
<p>Writing prose and writing code have much in common.  Many of the same techniques that make better prose also make better code.  In both cases, knowing what one has to work with (vocabulary and common phrases for prose and language features and class libraries for code) can make it easier to write particular effective prose or code.  Both types of writing also benefit tremendously from review.  Many of the same controversies surround both types of writing.</p>
    ]]></content>
  </entry>
  <entry>
    <title>Gosh, Things ARE Better for Developers These Days</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3130" />
    <id>http://www.javaworld.com/community/node/3130</id>
    <published>2009-06-28T19:23:56-04:00</published>
    <updated>2009-06-28T19:23:56-04:00</updated>
    <author>
      <name>Esther Schindler</name>
    </author>
    <category term="agile" />
    <category term="developer tools" />
    <category term="xml" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>Let's take a moment to appreciate how much has improved, in a developer's lot, over the last decade. In particular, contemplate how many "basic" programming concepts and "everybody knows" knowledge didn't exist in your life.</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Let's take a moment to appreciate how much has improved, in a developer's lot, over the last decade. In particular, contemplate how many "basic" programming concepts and "everybody knows" knowledge didn't exist in your life.</p>

<p>I've written a lot of computing nostalgia articles, from <a href="http://www.computerworld.com/action/article.do?command=viewArticleBasic&taxonomyName=Development&articleId=9132061&taxonomyId=11&pageNumber=1">Old-school programming techniques you probably don't miss</a> to <a href="http://www.cio.com/article/145853/Technologies_We_re_Glad_Are_Dead">Technologies We're Glad Are Dead</a>, and I sometimes fear that there's a little wistfulness in my voice. But the truth is that we (as technologists as well as software creators) are far better off than we used to be.</p>

<p>To highlight some of the improvements, in this post I identify several programming concepts that have entered the "ordinary" developers' awareness  in that last 10 years. (I got help from several <a href="http://www.linkedin.com/answers?viewQuestion=&questionID=488955&askerID=10138&goback=.hom.mid_1243156278">kind people on LinkedIn</a>.) Perhaps you'll appreciate how far we've come, and how much easier things have become for those who need to crank out working software on a boss's or client's unreasonable schedule. (Or at least we like to think they make things easier.)</p>

<p>The first problem in doing so, though, is deciding what we can claim "existed" a decade back. Because plenty of programming techniques were invented or discovered long before that... they just weren't considered ordinary, a concept that even the most naive of developers are familiar with. I'm not speaking here of competence, just awareness. Or, look at it this way: A decade back, you'd have considered knowledge of these unique enough to call out on a resume; today, it's common knowledge, or so endemic that the technique is built into your development tools.</p>

<p>For example, <strong>design patterns</strong> were around since <a href="http://www.informit.com/store/product.aspx?isbn=0201633612">the book was published in 1994</a>. But for years their use remained... not esoteric, exactly, but certainly something expected only from senior developers. Arguably, design pattern expertise was how you proved you <em>were</em> an expert. Nowadays, developer tools assume that you at least know what a design pattern is, if they don't offer features to align with them.</p>

<p>Another arguable category &mdash; is this "repackaged" or "new"?&mdash;is <strong>Software as a Service</strong>. SaaS existed, kind of, in 1999; we just called them Application Service Providers, and most of them failed because the companies behind them couldn't invent a business model, because they were over-protective of their APIs, because they required a not-yet-extant ubiquity of Internet resources (like common broadband access), and for many other primarily-business reasons. But this, too, was esoteric knowledge and not a topic that developers would discuss at any length. What <em>is</em> different in the ASP-to-SaaS transition, I think, is developers commonly writing applications building on public Web APIs. In 1999, it was still a big deal for your Internet application to integrate with FedEx tracking. Now, an entire Web application can be composed of glued-together APIs.</p>

<p><strong>XML existed</strong>, in 1999, but the first conference examining the technology and showing how to use it was in 2000. I attended that conference (and have a coffee mug to prove it). The big issue at the time was whether Microsoft's unique "extensions" had any relationship with the burgeoning XML standard. Everyone took for granted that XML would be a godsend to anyone who needed to exchange data with others, but nobody had invented the term <strong>Web services</strong> at the time. <strong>Service-oriented architecture</strong> was far in the future, though all of that, I think, was intimated by the initial promise of XML. And not just XML&nbsp;as a technology, but in its insistence on creating actual web standards to which everyone (even Microsoft) adhered.</p>

<p>One programming methodology that certainly fits in the "last 10 years" category is <strong>Agile development</strong>, as the <a href="http://www.agilemanifesto.org">Agile manifesto</a> dates from 2001</a>. I&nbsp;think Agile led to many other process improvements, and thus tool enhancements. As one LinkedIn friend pointed out, "Test-driven development, unit-testing tools (like NUnit and JUnit) and mocking frameworks have become widespread and are big improvement over the ways developers tested their code in the previous decade."</p>

<p>And hard as it may be to imagine, <strong>Microsoft's .NET</strong> didn't exist until 2002.</p>

<p>Surely, we must include Ajax on the list of advances in the last ten years. As with others, all the pieces were in place already, but turning a collection of useful techniques into a package of common tools has changed the way that developers work. The same might be said for any number of open-source development tools, from databases like MySQL to IDEs like Eclipse; initially considered "Well, they're okay for free," they are now overtaking and worrying the proprietary vendors. And while there were application servers ten years ago, in the last five or six years that we've seen the growth of useful meta-applications, such as content management systems, giving developers more than a rough scaffolding on which to build sites and applications.</p>

<p>But those just represent the tip of the iceberg. I expect you could name all sorts of other development techniques and tools that have vastly improved the quality of developers' lives. Care to add a few?</p>

    ]]></content>
  </entry>
  <entry>
    <title>Review: &quot;Programming Clojure&quot;, by Stu Halloway</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3129" />
    <id>http://www.javaworld.com/community/node/3129</id>
    <published>2009-06-28T01:34:56-04:00</published>
    <updated>2009-07-04T03:56:15-04:00</updated>
    <author>
      <name>Ted Neward</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><p>
<em><strong>(Disclaimer:</strong> In the spirit of full disclosure, Stu is a friend,<br />
fellow NFJS speaker, and former co-worker of mine from DevelopMentor.)</em>
</p>
<p>
I present this review to you in two parts.
</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
<em><strong>(Disclaimer:</strong> In the spirit of full disclosure, Stu is a friend,<br />
fellow NFJS speaker, and former co-worker of mine from DevelopMentor.)</em>
</p>
<p>
I present this review to you in two parts.
</p>
<p>
<strong>Short version:</strong> If you want to learn Clojure, and you're familiar<br />
with at least one programming language, you'll find this a great resource. If you<br />
don't already know a programming language, or if you already know Clojure, or if you're<br />
looking for &quot;best practices&quot; to cut-and-paste, you're going to be disappointed.
</p>
<p>
<strong>Long version:</strong> Recently, fellow NFJS speaker Stu Halloway decided<br />
to take up a new language, and came to Clojure. He found the language interesting<br />
enough to write a book on it, something he hasn't done since his Java days, and the<br />
result is a nice walk through the language and its environment for experienced Java<br />
developers who want to understand Clojure's language, concurrency concepts, and programming<br />
model.
</p>
<p>
Now, let's be 100% honest about this: if you're coming at this book expecting it to<br />
be a language reference, you will probably be disappointed (as <a href="http://www.amazon.com/review/R3NM9CKFWYFKAE/ref=cm_cr_rdp_perm" target="_blank">this<br />
guy</a> obviously is). Stu's not like that—he's not going to re-create material that's<br />
available elsewhere, or that can be found with an easy Google search. Stu will not<br />
waste your time that way—he wants to tell you a story, one that takes you from &quot;I'm<br />
a Java guy, but clueless about Lisp, dynamic languages, functional programming, concurrency,<br />
or macros&quot; to &quot;Wow. I know kung-fu.&quot; in the shortest path possible,<br />
but without trying to lobotomize you. He wants—no, <em>expects</em>—the readers of<br />
his book to be propping the text open with a cell phone on one side and the dinner<br />
plate on the other, craning your neck over to scan the pages and type in the examples<br />
into the REPL shell to try them out, see them work, then spend a few minutes experimenting<br />
with them before moving on to the next paragraph or page.
</p>
<p>
(Oh, I suppose you could just cut and paste them from the PDF version of the book,<br />
but where's the fun in that?)
</p>
<p>
The fact is, the <em>concepts</em> behind Clojure make up what's important to learn<br />
here, and readers of this book will come away like the panda from the movie, realizing<br />
that &quot;There is no Secret Ingredient&quot;, that the power of Clojure comes not<br />
from its super-secret language sauce or special libraries, but in the way Clojure<br />
programmers approach problems and think about programming. And for that reason, if<br />
you're a programmer—even if you don't program on the JVM—you really want to take a<br />
look at what Stu's talking about (and Rich Hickey is creating).
</p>
<p>
Just remember, cellphone and dinner plate. Otherwise you'll be missing out on so much.
</p>
<p></p>
<p>Enterprise consulting, mentoring or instruction. Java, C++, .NET or XML services.<br />
1-day or multi-day workshops available. <a href="mailto:ted@tedneward.com">Contact<br />
me for details</a>.</p>
    ]]></content>
  </entry>
  <entry>
    <title>Java Enums Are Inherently Serializable</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3125" />
    <id>http://www.javaworld.com/community/node/3125</id>
    <published>2009-06-27T02:09:00-04:00</published>
    <updated>2009-07-04T20:56:26-04:00</updated>
    <author>
      <name>dmarx</name>
    </author>
    <category term="Dustin" />
    <category term="Java (General)" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>More than once, I have seen code such as the following (without the comments I have added to point out flaws), in which a well-intentioned Java developer has ensured that their favorite <a href="http://java.sun.com/javase/6/docs/api/java/lang/Enum.html">Enum</a> explicitly declares that it is <a href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html">Serializable</a> and has even provided a <a href="http://marxsoftware.blogspot.com/2008/10/few-details-about-serialver.html">serialVersionUID</a> for it.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>More than once, I have seen code such as the following (without the comments I have added to point out flaws), in which a well-intentioned Java developer has ensured that their favorite <a href="http://java.sun.com/javase/6/docs/api/java/lang/Enum.html">Enum</a> explicitly declares that it is <a href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html">Serializable</a> and has even provided a <a href="http://marxsoftware.blogspot.com/2008/10/few-details-about-serialver.html">serialVersionUID</a> for it.</p>
<p>import java.io.Serializable;</p>
<p>/**<br /> * Enum example with unnecessary and ignored serialization specification<br /> * details.  The Enum is already Serializable and attempts to control its<br /> * serialization behavior are ignored.  See Section 1.12 ("Serialization of Enum<br /> * Constants") of the "Java Object Serialization Specification Version 6.0".<br /> */<br />public enum StateEnum implements Serializable<br />{<br />   ALABAMA("Alabama", "AL"),<br />   CALIFORNIA("California", "CA"),<br />   COLORADO("Colorado", "CO"),<br />   IDAHO("Idaho", "ID"),<br />   UTAH("Utah", "UT"),<br />   WYOMING("Wyoming", "WY");</p>
<p>   // Don't do this: Don't specify serialVersionUID for enums and don't use<br />   // an arbitrary constant such as 42L for all versions; use serialver on Sun JDK<br />   private static final long serialVersionUID = 42L; </p>
<p>   private String stateName;<br />   private String stateAbbreviation;</p>
<p>   StateEnum(final String newStateName, final String newStateAbbreviation)<br />   {<br />      this.stateName = newStateName;<br />      this.stateAbbreviation = newStateAbbreviation;<br />   }<br />}</p>
<p>Because enums are automatically <a href="http://www.deitel.com/articles/java_tutorials/20050923/IntroductionToObjectSerialization.html">Serializable</a> (see Javadoc API documentation for <a href="http://java.sun.com/javase/6/docs/api/java/lang/Enum.html">Enum</a>), there is <a href="http://www.coderanch.com/t/386060/Java-General-intermediate/java/enum-type-serializable-by-default">no need</a> to explicitly add the "implements Serializable" clause following the enum declaration.  Once this is removed, the import statement for the <a href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html">java.io.Serializable</a> interface can also be removed.  If you have any doubts about <code>Enum</code> being <code>Serializable</code>, run the HotSpot-provided <a href="http://marxsoftware.blogspot.com/2008/10/few-details-about-serialver.html">serialver</a> tool against your favorite enum that does not declare itself <code>Serializable</code>.  The tool will return <code>0L</code> for all enums.  When a class is not <code>Serializable</code>, this tool returns the message "Class --yourClassNameHere-- is not Serializable."  An example of this is shown in the next screen snapshot.</p>
<p><a href="http://4.bp.blogspot.com/_sDOe5HxTdMk/SkW6dx5NIwI/AAAAAAAABRw/yC3zngGPEGI/s1600-h/classIsNotSerializable_usesStateEnum.png"></a></p>
<p>The fact that <a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/serialver.html">serialver</a> returns <code>0L</code> for the enum’s <code>serialVersionUID</code> indicates that the enum is indeed <code>Serializable</code>.  The Javadoc also indicates this.  A third way to prove this to yourself is to use <code>instanceof</code> operator as shown in the next code sample.</p>
<p>import java.io.Serializable;</p>
<p>public class UsesStateEnum<br />{<br />   private StateEnum state;</p>
<p>   public UsesStateEnum(final StateEnum newState)<br />   {<br />      this.state = newState;<br />   }</p>
<p>   public StateEnum getState()<br />   {<br />      return this.state;<br />   }</p>
<p>   public void verifyEnumIsSerializable()<br />   {<br />      System.out.print("StateEnum instance of Serializable? ");<br />      System.out.println(this.state instanceof Serializable ? "yes" : "no");<br />   }</p>
<p>   public static void main(final String[] arguments)<br />   {<br />      System.out.println("Verify Enum is Serializable");<br />      final UsesStateEnum me = new UsesStateEnum(StateEnum.COLORADO);<br />      me.verifyEnumIsSerializable();<br />   }<br />}</p>
<p>As mentioned above, <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html">all Enums</a> have a <code>serialVersionUID</code> of <code>0L</code>.  Therefore, it is not necessary to specify one as is shown in the code above.  In fact, when one is specified, it is ignored anyway.  The example above intentionally used the hard-coded 42L used in Joshua Bloch’s <a href="http://java.sun.com/docs/books/effective/">Effective Java</a> example of how not to create a <code>serialVersionUID</code>.  As the screen snapshot below indicates, this explicitly specified value is ignored anyway:</p>
<p><a href="http://2.bp.blogspot.com/_sDOe5HxTdMk/SkW7NkGE5EI/AAAAAAAABR4/ZEoJiP132F4/s1600-h/allEnumsOLserialVersionUID_stateEnum.png"></a></p>
<p>The above screen snapshot also demonstrates an advantage of running <a href="http://java.sun.com/javase/6/docs/technotes/tools/solaris/serialver.html">serialver</a> against a class to generate the <code>serialVersionUID</code> rather than making up an arbitrary long value such as 42L.  By using the script, we get the <code>0L</code> result for all enums and improve our chances of remembering that enums all have <code>0L</code> for this value and don’t need it explicitly specified.</p>
<p>Although it does not hurt anything to unnecessarily specify that an enum implements <code>Serializable</code> or to even provide an ignored <code>serialVersionUID</code>, I prefer not to include these.  One might argue that at least adding "implements Serializable" communicates the intent to have an enum be <code>Serializable</code>, but my feeling is that this is a fundamental part of the language since <a href="http://java.sun.com/j2se/1.5.0/">J2SE 5</a> and such communication should be unnecessary.  When building a class that needs to be <code>Serializable</code>, using enum constituent pieces can be treated just the same as using Strings and primitives and the reference types corresponding to primitives.</p>
<p>All of the details I demonstrated and explained in this blog posting related to Enums being inherently Serializable are concisely described in two paragraphs of <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/serial-arch.html#6469">Section 1.12</a> ("Serialization of Enum Constants") of the <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/serialTOC.html">Java Object Serialization Specification</a>.</p>
<p><strong>Additional Resources</strong></p>
<p>&#8734; <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/serialTOC.html">Java Object Serialization Specification</a></p>
<p>&#8734; <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/serial-arch.html#6469">Serialization of Enum Constants</a></p>
<p>&#8734; <a href="http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp">Object Serialization: Frequently Asked Questions</a></p>
<p>&#8734; <a href="http://www.javaworld.com/javaworld/javaqa/2003-06/02-qa-0627-mythser.html">Into the Mist of Serialization Myths</a></p>
<p>&#8734; <a href="http://www.javaworld.com/javaworld/jw-07-2000/jw-0714-flatten.html">Flatten Your Objects: Discover the Secrets of the Java Serialization API</a></p>
<p>&#8734; <a href="http://www.javaworld.com/community/node/2915">Java Serialization Algorithm Revealed</a></p>
    ]]></content>
  </entry>
  <entry>
    <title>Oracle, an anxious Java community turns its eyes to you</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3124" />
    <id>http://www.javaworld.com/community/node/3124</id>
    <published>2009-06-26T05:30:37-04:00</published>
    <updated>2009-06-26T05:30:37-04:00</updated>
    <author>
      <name>Josh Fruhlinger</name>
    </author>
    <category term="anxiety" />
    <category term="Oracle" />
    <category term="Red Hat" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>Someday, someday soon, the Oracle-Sun deal will close, and we'll have more than just speculation to go on when we talk about what's in the future.  But until then, it's kind of fun to watch folks get anxious.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Someday, someday soon, the Oracle-Sun deal will close, and we'll have more than just speculation to go on when we talk about what's in the future.  But until then, it's kind of fun to watch folks get anxious.  In a conference call <a href="http://www.internetnews.com/bus-news/article.php/3826941/Red+Hat+CEO+Calls+on+Oracle+to+Keep+Java+Open.htm" target="_blank">Red Hat CEO Jim Whitehurst</a>, whose company is deep into Java middleware with its JBoss product, struck a note that sounded halfway between fear and bravado: "I think given that Java is not a standalone world, there's .NET out there as well, and I certainly think and hope that Oracle understands the importance of keeping Java very, very open and moving forward, recognizing that it's not a single world out there. Java has to compete with lightweight frameworks, has to compete with .NET, and so it's important to keep Java vibrant and thriving." Was this an attempt to plead with Oracle not to lock Java down tight, or was it a statement that there's other fish out in the sea for companies like Red Hat?  (The Mono project makes the idea of .NET on Linux not so silly as it might sound.)</p>

<p>Meanwhile, over at DevX Mike Rozlog asks <a href="http://www.devx.com/Java/Article/42218" target="_blank">three key questions about Java's future</a>, all centering around the JCP and the Apache-Sun dispute.  He manages to talk himself into the idea that Oracle will make these problems go away once it's in charge -- but lurking in the background seems to be the fear that things could get worse rather than better.</p>    ]]></content>
  </entry>
  <entry>
    <title>Viewing Names Bound to RMI Registry</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3123" />
    <id>http://www.javaworld.com/community/node/3123</id>
    <published>2009-06-26T01:37:00-04:00</published>
    <updated>2009-07-04T20:56:26-04:00</updated>
    <author>
      <name>dmarx</name>
    </author>
    <category term="Dustin" />
    <category term="glassfish" />
    <category term="groovy" />
    <category term="Java (General)" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>When working with Java <a href="http://java.sun.com/docs/books/tutorial/rmi/index.html">Remote Method Invocation</a> (<a href="http://www.javacoffeebreak.com/articles/javarmi/javarmi.html">RMI</a>), there are times when it is helpful to know which names are currently bound to a particular <a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/rmiregistry.html">rmiregistry</a> on a particular host/port combination.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>When working with Java <a href="http://java.sun.com/docs/books/tutorial/rmi/index.html">Remote Method Invocation</a> (<a href="http://www.javacoffeebreak.com/articles/javarmi/javarmi.html">RMI</a>), there are times when it is helpful to know which names are currently bound to a particular <a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/rmiregistry.html">rmiregistry</a> on a particular host/port combination.  This is especially true when debugging problems related to getting an RMI client unable to connect to an RMI server either because the server cannot be found (<a href="http://java.sun.com/javase/6/docs/api/java/rmi/NotBoundException.html">NotBoundException</a>) or because the server port is already bound to the provided name (<a href="http://java.sun.com/javase/6/docs/api/java/rmi/AlreadyBoundException.html">AlreadyBoundException</a>).</p>
<p>A simple Java application can be written that provides all named bindings for an RMI registry on a particular host and port.  The simple application demonstrated in this posting takes advantage of standard Java classes such as <a href="http://java.sun.com/javase/6/docs/api/java/rmi/registry/LocateRegistry.html">LocateRegistry</a>, <a href="http://java.sun.com/javase/6/docs/api/java/rmi/registry/Registry.html">Registry</a>, and other classes and exceptions in the <a href="http://java.sun.com/javase/6/docs/api/java/rmi/package-summary.html">java.rmi</a> and <a href="http://java.sun.com/javase/6/docs/api/java/rmi/registry/package-summary.html">java.rmi.registry packages</a>.  The code for this application is shown next.</p>
<p><strong>RmiPortNamesDisplay.java</strong></p>
<p>package dustin.examples.rmi;</p>
<p>import java.rmi.ConnectException;<br />import java.rmi.RemoteException;<br />import java.rmi.registry.LocateRegistry;<br />import java.rmi.registry.Registry;</p>
<p>/**<br /> * Display names bound to RMI registry on provided host and port.<br /> */<br />public class RmiPortNamesDisplay<br />{<br />   private final static String NEW_LINE = System.getProperty("line.separator");</p>
<p>   /**<br />    * Main executable function for printing out RMI registry names on provided<br />    * host and port.<br />    *<br />    * @param arguments Command-line arguments; Two expected: first is a String<br />    *    representing a host name ('localhost' works) and the second is an<br />    *    integer representing the port.<br />    */<br />   public static void main(final String[] arguments)<br />   {<br />      if (arguments.length &lt; 2)<br />      {<br />         System.err.println(<br />            "A host name (String) and a port (Integer) must be provided.");<br />         System.err.println(<br />            "\tExample: java dustin.examples.rmi.RmiPortNamesDisplay localhost 1099");<br />         System.exit(-2);<br />      }</p>
<p>      final String host = arguments[0];<br />      int port = 1099;<br />      try<br />      {<br />         port = Integer.valueOf(arguments[1]);<br />      }<br />      catch (NumberFormatException numericFormatEx)<br />      {<br />         System.err.println(<br />              "The provided port value [" + arguments[1] + "] is not an integer."<br />            + NEW_LINE + numericFormatEx.toString());<br />      }</p>
<p>      try<br />      {<br />         final Registry registry = LocateRegistry.getRegistry(host, port);<br />         final String[] boundNames = registry.list();<br />         System.out.println(<br />            "Names bound to RMI registry at host " + host + " and port " + port + ":");<br />         for (final String name : boundNames)<br />         {<br />            System.out.println("\t" + name);<br />         }<br />      }<br />      catch (ConnectException connectEx)<br />      {<br />         System.err.println(<br />              "ConnectionException - Are you certain an RMI registry is available at port "<br />            + port + "?" + NEW_LINE + connectEx.toString());<br />      }<br />      catch (RemoteException remoteEx)<br />      {<br />         System.err.println("RemoteException encountered: " + remoteEx.toString());<br />      }<br />   }<br />}</p>
<p>To test out the above application, I can start any service exposing an RMI interface.  For this example, I have started a <a href="https://glassfish.dev.java.net/">GlassFish</a> domain as shown in the next screen snapshot.</p>
<p><a href="http://4.bp.blogspot.com/_sDOe5HxTdMk/SkRj4f1gK1I/AAAAAAAABRY/BcRoTVDYfK4/s1600-h/runningGlassFishExposedPort8686.png"></a></p>
<p>The port on which GlassFish exposes its JMX RMI interface for management and monitoring is highlighted in the screen snapshot and is 8686.  When I run the simple RMI port names display application shown above on the same host on which I ran GlassFish, I can use "localhost" as the host.  When I run the above Java application, I see two bound names on the RMI registry on localhost at port 8686.  This is shown in the next screen snapshot.</p>
<p><a href="http://4.bp.blogspot.com/_sDOe5HxTdMk/SkRlG-ammCI/AAAAAAAABRg/HGSdt5NkFeM/s1600-h/glassFishRmiPortBoundNamesDisplayed.png"></a></p>
<p>From the results shown in the above image, we see that GlassFish exposes two named services on port 8686: jmxrmi and management/rmi-jmx-connector.</p>
<p>The simple application shown above uses standard Java libraries and classes, but also has a "script" feel.   It seems like what would really work well here is a script language that uses Java classes.  In other words, a scripting language that runs on the JVM such as <a href="http://jruby.codehaus.org/">JRuby</a> or <a href="http://groovy.codehaus.org/">Groovy</a> seems like the perfect fit.  With that in mind, the next code listing shows a Groovy implementation of the application written above in traditional Java.</p>
<p><strong>rmiPortNamesDisplay.groovy</strong></p>
<p>import java.rmi.ConnectException<br />import java.rmi.RemoteException<br />import java.rmi.registry.LocateRegistry<br />import java.rmi.registry.Registry</p>
<p>if (args.length &lt; 2)<br />{<br />   println "A host name (String) and a port (Integer) must be provided."<br />   println "\tExample: groovy rmiPortNamesDisplay localhost 1099"<br />   System.exit(-2)<br />}</p>
<p>host = args[0]<br />port = 1099<br />try<br />{<br />   port = Integer.valueOf(args[1])<br />}<br />catch (NumberFormatException numericFormatEx)<br />{<br />   println "The provided port value '${args[1]}' is not an integer."<br />   System.exit(-1)<br />}</p>
<p>registry = LocateRegistry.getRegistry(host, port)<br />boundNames = registry.list()<br />println "Names bound to RMI registry at host ${host} and port ${port}:"<br />boundNames.each{println "\t${it}"}</p>
<p>The above Groovy script, like the Java application from which it was adapted, can be run on the command line.  This is shown in the next screen snapshot.</p>
<p><a href="http://1.bp.blogspot.com/_sDOe5HxTdMk/SkRtv1qnloI/AAAAAAAABRo/gyt4hQ85Fzw/s1600-h/glassFishRmiPortBoundNamesDisplayedViaGroovy.png"></a></p>
<p>Besides the obvious syntactic differences, one advantage of writing something like this in Groovy is that it does not require an explicit compilation step.  The Java application above had to be compiled into a Java .class file first and then executed.  With Groovy, this is all done implicitly so that to the user it just feels like running a text-based script.  I am especially fond of using Groovy in cases like this where I wish to combine scripting features with accessibility to the JVM and standard Java libraries.</p>
<p><strong>Conclusion</strong></p>
<p>When working with RMI, there are times when it is important to know which named services are already bound to an RMI registry at a given host and port.  This blog posting has demonstrated use of the <code>LocateRegistry</code>, <code>Registry</code>, and other relevant classes to do this in a fairly easy manner with traditional Java and with Groovy.  It is a straightforward process to extend the Java application and Groovy script shown in this blog posting to cover multiple hosts and ports to, in effect, search for RMI registered names.</p>
    ]]></content>
  </entry>
  <entry>
    <title>Agile testing: a whole team approach</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3121" />
    <id>http://www.javaworld.com/community/node/3121</id>
    <published>2009-06-25T19:15:04-04:00</published>
    <updated>2009-07-01T15:56:20-04:00</updated>
    <author>
      <name>Andrew Glover</name>
    </author>
    <category term="agile" />
    <category term="Andy" />
    <category term="bdd" />
    <category term="ci" />
    <category term="Continuous Integration" />
    <category term="Developer Testing" />
    <category term="easyb" />
    <category term="Software Development" />
    <category term="software testing" />
    <category term="TDD" />
    <category term="unit testing" />
    <summary type="html"><![CDATA[<!--paging_filter--><p><a href="http://thediscoblog.com/2009/06/11/agile-testing-what-it-is/">Agile testing</a> is about two things: a <a href="http://thediscoblog.com/2009/06/17/agile-testing-a-whole-life-cycle-approach/">whole life-cycle</a> and whole team approach to testing. The whole life-cycle aspect stresses leveraging testing throughout a hip process as opposed to a distinct period. Likewise, a whole team approach welcomes all parties to the quality table as everyone (yes, that means all stakeholders) accepts responsibility for <em>building in</em> quality. </p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p><a href="http://thediscoblog.com/2009/06/11/agile-testing-what-it-is/">Agile testing</a> is about two things: a <a href="http://thediscoblog.com/2009/06/17/agile-testing-a-whole-life-cycle-approach/">whole life-cycle</a> and whole team approach to testing. The whole life-cycle aspect stresses leveraging testing throughout a hip process as opposed to a distinct period. Likewise, a whole team approach welcomes all parties to the quality table as everyone (yes, that means all stakeholders) accepts responsibility for <em>building in</em> quality. </p>
<p>While <a href="http://thediscoblog.com/2009/06/04/agile-testing-what-its-not/">traditional software methodologies</a> have the tendency to segment groups into logical units of responsibility, <a href="http://www.amazon.com/gp/product/0321534468?ie=UTF8&amp;tag=thdibl-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321534468">agile teams</a> favor a more collaborative approach that facilitates working along side various people and groups containing differing skill sets and expectations. That is, for example, the client begins to take responsibility for elaborating expectations through a working effort to understand how the process unfolds. What&#8217;s more, by working closely with a client, a team can better understand what is needed <em>and why</em>. As opposed to a test document fashioned from a bogue requirements document (often times done by various teams working separately), leveraging a <a href="http://thediscoblog.com/2008/10/16/lost-in-translation-stop-using-different-languages/">story in a collaborative manner</a> ensures all parties are effectively on the same page.  Thus, the customer (or some proxy there of), development, and QA are working together in the process of constructing stories and indeed leverage the same stories for all related assets.</p>
<p>Because it&#8217;s their bag, when Agile teams embrace stories as a fundamental means as to conveying requirements (i.e. features) along with a means for validating them, a natural tendency is for all parties to begin to own quality. That is, since everyone is aware of how to validate a feature, everyone begins to practice validating such features. In essence, a story facilitates leveraging both <a href="http://www.amazon.com/gp/product/0321146530?ie=UTF8&amp;tag=thdibl-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321146530">TDD</a> and functional testing (which are also both automated and exercised via <a href="http://www.amazon.com/gp/product/0321336380?ie=UTF8&amp;tag=thdibl-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321336380">CI</a>) .</p>
<p>What&#8217;s more, when the whole team both works together off of the same artifacts that are continuously verified, everyone can better understand the meaning of &#8220;done&#8221; &#8212; that being the question  &#8220;is feature x finished and ready for the client (or clients) to have?&#8221; Of course, if everyone has utilized the same artifact (i.e. a <a href="http://www.amazon.com/gp/product/0321205685?ie=UTF8&amp;tag=thdibl-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321205685">story</a>!) for both building and verifying a client&#8217;s expectations, then it is quite easy to check if the feature is done. </p>
<p>Thus, the whole team approach that leverages stories:</p>
<ul>
<li>ensures all hip parties see and understand the &#8220;big picture&#8221; of a particular project
<ul>
<li> that is, why someone wants an application (and its related features) built, which in turn further facilitates whole team ownership (along with more effective testing!)</li>
</ul>
</li>
<li>helps teams figure out the definition of done</li>
</ul>
<p>Obtaining these benefits is a matter of providing a means for all parties on a team to collaborate, which is often found in leveraging a story. Plus, visibility into overall team progress as facilitated via CI and automation. The whole team approach also meets the original goal of software testing  &#8212; that being the assurance that high quality code is delivered to interested parties. Teaming also reduces the tendency to throw up barriers that often plague efficiency.</p>
<p>Agile testing boils down to two fundamental changes, baby, that differentiate it from traditional software testing &#8212; both the notion that testing isn&#8217;t a phase but a whole life-cycle approach and that the entire team works together towards shared goals. Agile testing complements a highly efficient software development life-cycle and ultimately produces <em>better software faster</em>. </p>
<p>You can now follow <a href="http://twitter.com/thediscoblog">The Disco Blog on Twitter</a>, baby!</p>
    ]]></content>
  </entry>
  <entry>
    <title>Epsilon 1.0.0 Alpha Preview Now Available</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3119" />
    <id>http://www.javaworld.com/community/node/3119</id>
    <published>2009-06-25T08:25:51-04:00</published>
    <updated>2009-06-25T08:29:52-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="java" />
    <category term="latency" />
    <category term="monitoring" />
    <category term="performance" />
    <category term="Spring" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>
<a href="http://www.obix-labs.com">Epsilon</a> is a lightweight tool for monitoring and tracking the performance of Java applications in real time. It supports integration and configuration via Spring, including Spring AOP. Download from: <a href="http://www.obix-labs.com" title="http://www.obix-labs.com">http://www.obix-labs.com</a>
</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
<a href="http://www.obix-labs.com">Epsilon</a> is a lightweight tool for monitoring and tracking the performance of Java applications in real time. It supports integration and configuration via Spring, including Spring AOP. Download from: <a href="http://www.obix-labs.com" title="http://www.obix-labs.com">http://www.obix-labs.com</a>
</p>
<p>
<a href="http://www.obix-labs.com">Epsilon</a> allows developers to set processing/performance benchmarks for an application, and monitors these in real-time as the application services requests. In cases where these benchmarks are breached, it can issue a notification (e.g. via email or by logging an alert) to one or more destinations. Amongst its many features are:
</p>
<p><ul>
<li>
<a href="http://www.springframework.org">Spring</a> support: Epsilon can be integrated and configured via Spring.
</li>
<li>
Non-intrusive: It can be embedded into applications by employing a <a href="http://www.springframework.org">Spring AOP</a> interceptor; thus removing the need for explicit references in application code.
</li>
<li>
Simple to embed: Epsilon can also be embedded directly into application code in a manner similar to that used for logging.
</li>
<li>
Statistical and fixed benchmarks: Application performance can be monitored in reference to the historically observed performance/latency of an application. Alternatively monitoring can be based on fixed latency caps.
</li>
<li>
Notifications callback: Email and log alert functionality is provided in the current release; however, users can also implement a simple callback interface to provide custom notification functionality.
</li>
<li>
Highly performant and lightweight: Epsilon will not skew the performance of the monitored application as it functions in an asynchronous and non-blocking manner. Neither will it add unnecessarily to the memory footprint of the monitored application.
</li>
<li>
Historical data: It can be configured to keep a specified amount of historical data, thus making it possible to utilize the collected data for other purposes.
</li>
<li>
Easy to extend
</li>
<li>
Free and open source
</li>
</ul>
</p>
    ]]></content>
  </entry>
  <entry>
    <title>Thread Analysis with VisualVM</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3117" />
    <id>http://www.javaworld.com/community/node/3117</id>
    <published>2009-06-25T01:27:00-04:00</published>
    <updated>2009-07-04T20:56:26-04:00</updated>
    <author>
      <name>dmarx</name>
    </author>
    <category term="Dustin" />
    <category term="Java (General)" />
    <category term="VisualVM" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>Although <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jstack.html">jstack</a> (Java Stack Trace) is a useful tool for learning more about a how a Java thread is behaving, <a href="http://java.sun.com/javase/6/docs/technotes/guides/visualvm/">VisualVM</a> is an even easier method for obtaining the same type of information.</p>
<p>It is easy to run <code>jstack</code> as demonstrated in the next screen snapshot:</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Although <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jstack.html">jstack</a> (Java Stack Trace) is a useful tool for learning more about a how a Java thread is behaving, <a href="http://java.sun.com/javase/6/docs/technotes/guides/visualvm/">VisualVM</a> is an even easier method for obtaining the same type of information.</p>
<p>It is easy to run <code>jstack</code> as demonstrated in the next screen snapshot:</p>
<p><a href="http://3.bp.blogspot.com/_sDOe5HxTdMk/SkMLbmAvsHI/AAAAAAAABQo/-jWlPtOdxwg/s1600-h/basicJstackUseHelpRun.png"></a></p>
<p>Only the top portion of the generated stack trace information is shown above.  The output of an entire <code>jstack</code> run looks similar to that which follows:</p>
<p>2009-06-24 23:25:26<br />Full thread dump Java HotSpot(TM) Client VM (14.0-b16 mixed mode, sharing):</p>
<p>"RMI Scheduler(0)" daemon prio=6 tid=0x04bb4c00 nid=0x126c waiting on condition [0x048ef000]<br />   java.lang.Thread.State: WAITING (parking)<br /> at sun.misc.Unsafe.park(Native Method)<br /> - parking to wait for  &lt;0x2492dac8&gt; (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)<br /> at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)<br /> at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)<br /> at java.util.concurrent.DelayQueue.take(DelayQueue.java:160)<br /> at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:583)<br /> at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:576)<br /> at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)<br /> at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)<br /> at java.lang.Thread.run(Thread.java:619)</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"RMI TCP Accept-0" daemon prio=6 tid=0x023bfc00 nid=0xa74 runnable [0x0483f000]<br />   java.lang.Thread.State: RUNNABLE<br /> at java.net.PlainSocketImpl.socketAccept(Native Method)<br /> at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:390)<br /> - locked &lt;0x2492dc48&gt; (a java.net.SocksSocketImpl)<br /> at java.net.ServerSocket.implAccept(ServerSocket.java:453)<br /> at java.net.ServerSocket.accept(ServerSocket.java:421)<br /> at sun.management.jmxremote.LocalRMIServerSocketFactory$1.accept(LocalRMIServerSocketFactory.java:34)<br /> at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.executeAcceptLoop(TCPTransport.java:369)<br /> at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.run(TCPTransport.java:341)<br /> at java.lang.Thread.run(Thread.java:619)</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"Low Memory Detector" daemon prio=6 tid=0x02348000 nid=0xec4 runnable [0x00000000]<br />   java.lang.Thread.State: RUNNABLE</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"CompilerThread0" daemon prio=10 tid=0x02343000 nid=0x108 waiting on condition [0x00000000]<br />   java.lang.Thread.State: RUNNABLE</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"Attach Listener" daemon prio=10 tid=0x02342800 nid=0xf6c waiting on condition [0x00000000]<br />   java.lang.Thread.State: RUNNABLE</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"Signal Dispatcher" daemon prio=10 tid=0x02339c00 nid=0xac runnable [0x00000000]<br />   java.lang.Thread.State: RUNNABLE</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"Finalizer" daemon prio=8 tid=0x022f4000 nid=0xd14 in Object.wait() [0x044cf000]<br />   java.lang.Thread.State: WAITING (on object monitor)<br /> at java.lang.Object.wait(Native Method)<br /> - waiting on &lt;0x248ee9a0&gt; (a java.lang.ref.ReferenceQueue$Lock)<br /> at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)<br /> - locked &lt;0x248ee9a0&gt; (a java.lang.ref.ReferenceQueue$Lock)<br /> at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)<br /> at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"Reference Handler" daemon prio=10 tid=0x022f2c00 nid=0x1198 in Object.wait() [0x0240f000]<br />   java.lang.Thread.State: WAITING (on object monitor)<br /> at java.lang.Object.wait(Native Method)<br /> - waiting on &lt;0x248eea28&gt; (a java.lang.ref.Reference$Lock)<br /> at java.lang.Object.wait(Object.java:485)<br /> at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)<br /> - locked &lt;0x248eea28&gt; (a java.lang.ref.Reference$Lock)</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"main" prio=6 tid=0x00209000 nid=0x1134 runnable [0x002af000]<br />   java.lang.Thread.State: RUNNABLE<br /> at java.util.Arrays.copyOf(Arrays.java:2882)<br /> at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)<br /> at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:390)<br /> at java.lang.StringBuilder.append(StringBuilder.java:119)<br /> at dustin.examples.tools.AnalyzableImpl.loopProvidedNumberOfTimes(AnalyzableImpl.java:48)<br /> at dustin.examples.tools.AnalyzableImpl.main(AnalyzableImpl.java:80)</p>
<p>   Locked ownable synchronizers:<br /> - None</p>
<p>"VM Thread" prio=10 tid=0x022f1400 nid=0x10c runnable </p>
<p>"VM Periodic Task Thread" prio=10 tid=0x02348c00 nid=0x278 waiting on condition </p>
<p>JNI global references: 872</p>
<p><a href="https://visualvm.dev.java.net/">VisualVM</a> makes it easy to <a href="http://java.sun.com/javase/6/docs/technotes/guides/visualvm/threads.html">monitor application threads</a>.  <a href="http://java.dzone.com/news/visual-vm-free-and-open-source">VisualVM</a> offers the capability to generate and view the <code>jstack</code>-generated stack trace.  The first way to do this is to right-click on the appropriate Java process and select the option "Thread Dump."  This will generate a thread dump file whose name appears under the selected Java process as shown in the following screen snapshot.</p>
<p><a href="http://3.bp.blogspot.com/_sDOe5HxTdMk/SkMPnfV0qiI/AAAAAAAABQw/tWQAhWgyEmg/s1600-h/visualVmRightClickJavaProcessSelectThreadDump.png"></a></p>
<p>A second way to get the thread dump generated in VisualVM is to use the "Threads" tab and click on the button "Thread Dump."  This button is demonstrated in the next screen snapshot.</p>
<p><a href="http://1.bp.blogspot.com/_sDOe5HxTdMk/SkMQb_d4XCI/AAAAAAAABQ4/8UcceIIT5Mg/s1600-h/visualVmThreadDumpButtonOnThreadsTab.png"></a></p>
<p>Whether the right-click option is used or the "Thread Dump" button is pressed, VisualVM generates <code>jstack</code> thread dump output file and displays it as shown in the next screen snapshot.</p>
<p><a href="http://4.bp.blogspot.com/_sDOe5HxTdMk/SkMREdJ9teI/AAAAAAAABRA/4ug-bJv6vjI/s1600-h/visualVmDisplayedThreadDump.png"></a></p>
<p>As discussed and demonstrated, VisualVM allows for easy generation of a stack trace dump with <code>jstack</code>.  However, VisualVM provides much more than that for thread analysis.</p>
<p>The screen snapshot above that showed the "Thread Dump" button also conveniently demonstrates VisualVM's Timeline tab that demonstrates in a live fashion the "live" threads.  These colored horizontal bars represent individual threads.  Their display is enabled because the "Threads visualization" checkbox is checked.</p>
<p>Another useful tab on VisualVM is the "Threads" "Table" view that provides textual overview information on the threads.  This is demonstrated in the next screen snapshot.</p>
<p><a href="http://2.bp.blogspot.com/_sDOe5HxTdMk/SkMS0MPoANI/AAAAAAAABRI/KAnfSx4g3i0/s1600-h/visualVmThreadTableDetails.png"></a></p>
<p>Any individual thread can be clicked on to see the detailed Threads view.  This view, also under the "Threads" tab in VisualVM.  When "Threads visualization" is checked, a pie chart is included that graphically indicates what each thread is doing.  This is demonstrated in the next screen snapshot.</p>
<p><a href="http://4.bp.blogspot.com/_sDOe5HxTdMk/SkMTiq_wcbI/AAAAAAAABRQ/Qj8pUq2UlU4/s1600-h/visualVmThreadsDetails.png"></a></p>
<p><strong>Conclusion</strong></p>
<p>The <code>jstack</code> tool is a useful command-line tool, but VisualVM provides the same capabilities along with a significantly improved presentation and details.</p>
    ]]></content>
  </entry>
</feed>
