Blog Posts tagged with: java-next

Sep 24 2008

Comments

Java.next Overview

As we reach the middle of our second decade of Java experience, the community has learned a lot about software development. Many of our best ideas on how to use a Java Virtual Machine (JVM) are now being baked into more advanced languages for the JVM. These languages tend to provide two significant advantages:

  • They reduce the amount of ceremony in your code, allowing you to focus on the essence of the problem you are solving.
  • They enable some degree of functional programming style. Think of it as a dash of verb-oriented programming to spice up your noun-oriented programming.

I have picked four "Java.next" languages to demonstrate these concepts: Clojure, Groovy, JRuby, and Scala. I have written a series of articles and conference talks describing how these languages can make teams more productive.

This page is the top-level table of contents for Java.next, and I will update the links below as new articles and talks become available.

Articles on Java.next

Conference talks on Java.next

Seeing a talk

If you are interested in hearing me speak on Java.next, check the event schedule, or contact Relevance (info@thinkrelevance.com) to schedule an event near you.

Sep 10 2008

Comments

Java.next #4: Immutability

This is Part Four of a series of articles on Java.next. In Part Four, I will begin to explore how the Java.next languages (JRuby, Groovy, Clojure, and Scala) deal with concurrency. Concurrency is a big topic, so I will subdivide it, narrowing my focus in this part to how the Java.next languages support immutability.

Why concurrency?

Over the last decade, most programmers have written code with little concern for concurrency. Often this has caused problems later, when programs needed to be used in a more concurrent setting. This is only going to get worse: in the future, everything is concurrent.

Why don't programmers do a better job with concurrency? Because it is hard. Read the excellent Java Concurrency in Practice (JCIP), and you will come away impressed with all the clever work that has gone into making Java a good environment for writing concurrent applications. But may also come away thinking "Who is smart enough to get this kind of code right in production?"

Not many people can, and the experts agree that we need an entirely different paradigm for writing concurrent applications. It may even be the case that supporting concurrency is the number one priority for Java.next.

Why immutability?

One of the most difficult things about writing concurrent programs is deciding how to protect mutable shared state. Java provides a locking primitive, synchronized, but locking primitives are difficult to use. You have to worry about

  • data corruption (if you lock too little)
  • deadlock (if you lock too much)
  • performance degradation (even if you get it right)

To make matters worse, it is generally impractical to write automated tests that explore the various possible interleavings of events.

Immutability solves all these problems of locking, by removing the need for ever locking at all. Immutable state can always be shared safely. Nobody can ever see a corrupt value by definition, as values never change.

All of the Java.next languages support immutability to some degree, as I will show below.

Immutability in JRuby

JCIP uses a ThreeStooges class as an extremely simple example for creating immutable objects in Java. Continuing the theme of that example, here is JRuby's immutable stooges:

  require 'set'

  class ThreeStooges
    def initialize(*names)
      @stooges = Set.new(names)
      @stooges.freeze
      self.freeze
    end
    def stooge?(name)
      @stooges.member?(name)
    end
  end

In Ruby, you can set immutability on a per-instance basis, as opposed to a per-class basis. A particular object can become immutable by calling freeze. If the internal components of that object are not primitive, they will need to freeze as well. So, in the constructor above, I freeze the two things at risk of changing: stooges and self.

While immutability is possible in Ruby, be warned. Heavy use of freeze to enable safe concurrency is far from idiomatic.

Immutability in Groovy

In Groovy, the ThreeStooges class looks and works like Java, but prettier:

  class ThreeStooges { 
    private final Set<String> stooges;
    ThreeStooges(String... args) {
      stooges = args as HashSet<String>;
    }
    boolean isStooge(String name) {
      return stooges.contains(name); 
    }
  }

The important details here are that the internal stooges collection is

  • final (cannot be changed after the object is created)
  • private (cannot be accessed outside the object itself)

I could also wrap stooges with unmodifiableSet, but since the ThreeStooges class already wraps stooges without exposing a modifying method, the second wrap is redundant.

Immutability in Scala

In JRuby and Groovy, immutability is possible. In Scala, immutability is preferred. The default collection classes are immutable, so ThreeStooges is just

  class ThreeStooges(names: String*) {
    private val stooges = Set() ++ names
    def isStooge(name: String) = stooges(name)
  }

A few observations here:

  • In Scala, fields must be declared val (immutable) or var (changeable). Scala style encourages you to use val where possible.
  • Scala's Set is immutable.

I find that Scala's inline constructor syntax and braces-free method definition syntax make the Scala definition easier to read than the JRuby or Groovy versions.

Immutability in Clojure

In Clojure, immutability is the default. In fact, everything is immutable, with only two exceptions:

  • calling down into Java APIs (the Clojure version of assembly language)
  • a few data structures which are specifically designed to support Software Transactional Memory (more on this in a later post)

So, the three-stooges can just be a set:

  (defn three-stooges [& names] (set names))
  (defn is-stooge? [name stooges] (stooges name))

A few observations:

  • [& names] is Clojure's varargs syntax.
  • A set can be placed in function position (first item in a list). So (stooges name) can be read as "find name in the set stooges"

Putting immutables to work

To see how immutables can simplify an implementation, consider the Factorizer servlet example from JCIP. The objectives of this example are to

  • calculate the prime factorization of a number
  • cache the most recent factorization
  • use the cached answer where possible, and track the frequency of cache hits
  • track the total number of factorizations

Here is a Java version of the factorizer using synchronized blocks, and stripped down to bare essentials for clarity:

  import java.math.BigInteger;

  public class CachedFactorizer {
      private BigInteger ;
      private BigInteger[] lastFactors;
      private long hits;
      private long cacheHits;

      public void factors(BigInteger i) {
          BigInteger[] factors = null;
          synchronized (this) {
              ++hits;
              if (i.equals(lastNumber)) {
                  ++cacheHits;
                  factors = lastFactors.clone();
              }
          }
          if (factors == null) {
              factors = factor(i);
              synchronized (this) {
                  lastNumber = i;
                  lastFactors = factors.clone();
              }
          }
          return factors;
      }
  }

In order for the CachedFactorizer to be correct and efficient, you need to think carefully about where the synchronized blocks should go. In the example above, there are two synchronized blocks. The first block checks the cache, and updates the counters. It protects:

  • read and write of hits
  • read and write of cacheHits
  • read of lastFactors

The second block updates the cache. It protects:

  • write of lastNumber
  • write of lastFactors

To make sure you understand the approach, ask yourself the following questions:

  • Could the first synchronized block be split into multiple, more granular locks? Would this likely be faster or slower?
  • What about the second block?
  • What operations are unprotected by locks? Is this safe?
  • Would a simple, single-lock approach be correct? Under what circumstances would it perform well?

That's a lot to think about. Now, let's consider the same example, but using immutable data structures.

A Clojure cached-factor

Here is one Clojure approach to cached-factor:

  (def #^AtomicLong hits (AtomicLong. 0))
  (def #^AtomicReference cache (AtomicReference. {:n nil :factors nil}))
  (def #^AtomicLong cache-hits (AtomicLong. 0))

  (defn cached-factor [n]
   (.incrementAndGet hits)
   (let [cached (.get cache)]
     (if (= n (cached :n))
       (do (.incrementAndGet cache-hits)
         (cached :factors))
       (let [factors (factor n)]
         (.set cache {:n n :factors factors})
         factors))))

There are several things to notice here:

  • The hits, cache, and cache-hits take advantage of Java 5's atomic wrapper classes. (The #^ClassName syntax adds type information.)
  • There are no synchronized blocks anywhere.
  • Even though there are no synchronized blocks, you still have to think about the semantics of concurrency. The incrementAndGet method is used to update the two hit counters, and the cache is pulled into a local variable to avoid inconsistent reads.

The real key to this approach, however, is storing a Clojure map in an AtomicReference. Because Clojure data structures are immutable, they can benefit from an AtomicReference in a way that mutable classes cannot.

The immutable approach looks only a little simpler in this small example. But the benefit of using immutable data increases when you compose objects together. If you wanted to compose the synchronized version with another object, you would have have to dig back into the internals of both objects, study their locks, and pick a new lock strategy to cover the two objects together. Composing operations with immutable objects is much easier.

A Scala CachedFactor

Since Scala's default collections are immutable, a Scala approach can closely parallel the Clojure code above:

  class CachedFactorizer {
    case class Cache(val n: Int, val factors: List[Int])
    val hits = new AtomicLong()
    val cache = new AtomicReference[Cache](Cache(2, calculateFactors(2)))
    val cacheHits = new AtomicLong()

    def factor(n: Int) = {
      hits.incrementAndGet
      val cached = cache.get
      if (cached.n == n) {
        cacheHits.incrementAndGet
        cached.factors
      } else {
        val factors = calculateFactors(n)
        cache.set(Cache(n, factors))
        factors
      }
    }

While this is similar to the Clojure approach, the difference is instructive. While the Clojure version stores the cache as a simple Map, the Scala version introduces a strongly-typed Cache class for the cache of values and their factors. The differences here are intended to idiomatic. Either approach could work in either language.

What about the JRuby and Groovy examples?

Could you write the example above in Groovy, JRuby, or even Java? Yes, but it would be non-idiomatic, even ugly. I am not going to show the JRuby and Groovy versions here, because those languages do not offer any concurrency-specific advantages over Java. Scala and Clojure, on the other hand, don't just make immutable objects possible. They make them easy and idiomatic.

Languages are designed to support certain priorities, inevitably at the expense of others. By making immutability a preferred option (Scala) or the standard (Clojure), these languages are encouraging a different paradigm for concurrent applications.

Languages are not about what they make possible, but about what they make beautiful. Clojure and Scala aim to make concurrent programs beautiful, and their preference for immutability is but the tip of the iceberg. In the next installment of this series, I will explore how Clojure and Scala enable concurrent programs through actors, agents, and software transactional memory.


Notes

  • This article is based on the talk Java.next #4: Concurrency . Check the schedule for a talk near you.
  • Thanks to Greg Vaughn and Glenn Vanderburg for their feedback on a draft of this article.
  • Thanks to Rich Hickey for suggesting several Clojure versions of the factorizer example.
  • Feedback on how to improve these examples is most welcome!

Sep 09 2008

Comments

Java.next Presentation #4: Concurrency

Programming concurrency is hard, but the Java.next languages can make things easier. In this talk (Part 4 of the Java.next series), I will demonstrate how to write concurrent applications in Clojure, Groovy, JRuby, and Scala.

Topics will include

  • calling the java.util.concurrent APIs
  • why locks are harmful
  • using immutable objects
  • Scala's actor model
  • Clojure's Software Transactional Memory and Agents

For more information, see the following article on the Relevance blog:

Aug 26 2008

Comments

Java.next #3: Dispatch

This is Part Three of a series of articles on Java.next. In Part Three, I will explore how the Java.next languages (JRuby, Groovy, Clojure, and Scala) support dispatch.

For my purposes here, dispatch is a broad term covering various methods of dynamically choosing behavior: single dispatch, switch/case, pattern matching and multiple dispatch. These concepts are not generally grouped together, but they should be. They are used to solve similar problems, albeit in very different ways.

Single dispatch

Let me start with single dispatch. In Java, methods can be selected based on the type of the object they are invoked on. All the Java.next languages support single dispatch, too:

  ; clojure
  (fly vehicle speed)

  // Java, Groovy, or Scala
  vehicle.fly(speed)            

  # ruby
  vehicle.fly speed

In all of these languages, the actual implementation of fly can vary depending on the run-time type of vehicle. (Clojure also supports multiple dispatch, where the implementation can vary based on the type of speed -- more on that later.)

Better switching

Another way to dynamically choose behavior is with a switch statement. Java has a simple switch statement, based on its historical kinship with C and C++. Switch statements have gotten a bad name, so much so that programmers are encouraged to replace them with polymorphism where possible.

This anti-switching bias is based on the limited kind of switching allowed in languages such as Java. In Java.next, there is a different story. The Java.next languages all have powerful switching capabilities, allowing you to switch on any criteria you like. As an example, consider a method that calculates a letter grade, taking input that is either a number or letter grade.

Ruby's case statement

Here is letter_grade in Ruby:

  def letter_grade(val)
    case val
      when 90..100: 'A'
      when 80...90:  'B'
      when 70...80:  'C'
      when 60...70:  'D'
      when 0...60:   'F'
      when /[ABCDF]/i: val.upcase
      else raise "Not a valid grade: #{val}"
    end
  end

In Ruby, the switch/case variant is called case. The Ruby when clause can take arbitrary expressions. Above you see ranges and regular expressions side-by-side in the same case expression. In general, the when clause expects objects that implement a well-known threequals method, ===. Many Ruby objects have sensible === implementations: ranges match numbers in the range, regular expressions match strings containing the regular expression, classes match instances of the class, etc. But any object can implement ===, so you can implement arbitrarily complex dispatch with Ruby case.

Groovy's switch statement

Here is letterGrade in Groovy:

  def letterGrade(val) {
    switch(val) {
     case 90..100: return 'A'
     case 80..<90:  return 'B'
     case 70..<80:  return 'C'
     case 60..<70:  return 'D'
     case 0..<60:   return 'F'
     case ~"[ABCDFabcdf]": return val.toUpperCase()
      default:  throw new 
                IllegalArgumentException("Invalid grade: $val")
    }
  }

In Groovy, the switch/case variant is called switch. If you compare this code with JRuby, you will see minor syntactic differences:

  • Groovy switch keeps faith with Java, so you have to return or break out
  • Groovy uses default where Ruby uses else.
  • Groovy's top-exclusive range uses ..< whereas Ruby's uses ... .
  • Groovy uses isCase instead of ===. (This is not visible in the code sample, but you would need it to test case matches individually.)

The general ideas are the same. Both JRuby and Groovy provide far more powerful and general approaches than Java's switch.

Clojure's cond function

In clojure, as in many Lisps, you can switch on arbitrary functions using cond. One possible approach to letter-grade would be:

  (defn letter-grade [grade]
    (cond 
     (in grade 90 100) "A"
     (in grade 80 90) "B"
     (in grade 70 80) "C"
     (in grade 60 70) "D"
     (in grade 0 60) "F"
     (re-find #"[ABCDFabcdf]" grade) (.toUpperCase grade)))

In Clojure, regular expressions look like #"...". The in function above is not part of Clojure. I wrote the code the way I wanted it to read, and then wrote this function:

  (defn in [grade low high]
     (and (number? grade) (<= low grade high)))

In Clojure, I probably wouldn't use a regular expression for the letter-matching step, but I wrote the example that way for symmetry with the others.

Clojure's cond is just the tip of the iceberg. Clojure-contrib includes a set of macros for other variants of switch/case, and later in this article I will demonstrate Clojure's multiple dispatch.

Scala's pattern matching

Scala's pattern matching is a powerful generalization of the switch/case idiom in many programming languages. Scala provides out of the box support for pattern matching on

  • constants
  • variables (which can be used in the match result)
  • constructors
  • sequences
  • tuples
  • types

With pattern matching, implementing letterGrade is a snap:

  val VALID_GRADES = Set("A", "B", "C", "D", "F")
  def letterGrade(value: Any) : String = value match {
    case x:Int if (90 to 100).contains(x) => "A"
    case x:Int if (80 to 90).contains(x) => "B"
    case x:Int if (70 to 80).contains(x) => "C"
    case x:Int if (60 to 70).contains(x) => "D"
    case x:Int if (0 to 60).contains(x) => "F"
    case x:String if VALID_GRADES(x.toUpperCase) => x.toUpperCase()
  }

In this implementation, numeric grades and letter grades are both matched first by type. Then, case expressions also allow a guard that limits possible matches to some condition. So, for example, the first case above matches only if value is an Int (type match) and between 90 and 100 (the guard).

Scala's guard expressions are cool, but the combination of type+guard does not exactly parallel the other implementations of letterGrade, which rely on arbitrary predicates in case expressions. Scala can do this too: Scala extractors allow you to create arbitrary patterns. Here is one approach to letterGrade using extractors:

  def letterGrade(value: Any) : String = value match {
    case NumericA(value) => "A"
    case NumericB(value) => "B"
    case NumericC(value) => "C"
    case NumericD(value) => "D"
    case NumericF(value) => "F"
    case LetterGrade(value) => value
  }

Behind the scenes, NumericA and friends are objects that implement an unapply method to determine if and how a value should match the pattern.

A more complex example

Scala's pattern matching is much more general than the letter grade example shows. To see this, check out Daniel Spiewak's series introducing Scala for Java programmers. In Part 4, he gives an example of pattern-matching working in conjunction with case classes, which I will explore below.

Scala's case classes

Case classes offer several interesting properties when compared to regular classes:

  • Case classes automatically get a factory method, e.g. Foo(1) instead of new Foo(1)
  • Case classes automatically get reasonable implementations for toString, hashCode, and equals.

These properties are so useful that Scala programmers use case classes for all kinds of things. But their true purpose is revealed in conjunction with patterns: Case classes work directly with pattern matching, without having to write an extractor as in the previous example.

  class Color(val red:Int, val green:Int, val blue:Int)

  case class Red(r:Int) extends Color(r, 0, 0)
  case class Green(g:Int) extends Color(0, g, 0)
  case class Blue(b:Int) extends Color(0, 0, b)

  def printColor(c:Color) = c match {
    case Red(v) => println("Red: " + v)
    case Green(v) => println("Green: " + v)
    case Blue(v) => println("Blue: " + v)

    case col:Color => {
      print("R: " + col.red + ", ")
      print("G: " + col.green + ", ")
      println("B: " + col.blue)
    }

    case null => println("Invalid color")
  }

The printColor method pattern-matches Red, Green, and Blue to provide special behavior for basic colors. Because these are case classes we can capture the actual color value v. All other colors fall through to a general Color, which prints a more generic message.

Clojure's defmulti

Scala's pattern-matching is a signature feature of the language. How do the other Java.next languages compare? To implement printColor in Clojure, I begin by defining a structure to capture a color:

  (defstruct color :red :green :blue)

Where the Scala example defined basic colors with case classes, in Clojure I can use functions:

  (defn red [v] (struct color v 0 0))
  (defn green [v] (struct color 0 v 0))
  (defn blue [v] (struct color 0 0 v))

Now for the fun part. I will define a multimethod named color-string, which dispatches based on which basic colors are present in the color struct.

  (defmulti color-string basic-colors-in)

basic-colors-in is a dispatch function that reports which colors have nonzero values:

  (defn basic-colors-in [color]
    (for [[k v] color :when (not= v 0)] k))

Now I can define multiple implementations of color-string. The basic syntax is

  (defmethod method-name dispatch-value function-body)

So for the three pure colors, I can define color-string as

  (defmethod color-string [:red] [color] (str "Red: " (:red color)))
  (defmethod color-string [:green] [color] (str "Green: " (:green color)))
  (defmethod color-string [:blue] [color] (str "Blue: " (:blue color)))

I can also provide a catch-all implementation by specifying a dispatch-value of :default:

  (defmethod color-string :default [color] 
    (str "Red: " (:red color) ", Green: " (:green color) ", Blue: " (:blue color)))

Multimethods are more powerful than polymorphic single dispatch in two important ways:

  1. With polymorphic single dispatch, the dispatch function is always the type of the the first argument. With multimethods, the dispatch function can be any arbitrary function, e.g. basic-colors-in above.
  2. With polymorphic single dispatch, polymorphism is limited to the first parameter. The dispatch function for a multimethod can look at all parameters, and vary based on any of them. (This feature is not needed in the color-string example above, but see Runtime Polymorphism for an example.)

Like Scala's pattern matching, Clojure's defmulti provides an extremely powerful and extensible dispatch mechanism.

Accidently blue

Both the Scala and Clojure code above take special action for colors that are declared to be pure blue:

  // Scala
  scala> printColor(Blue(10))          
  Blue: 10
  ; Clojure
  user=> (color-string (blue 10))
  "Blue: 10"

What about colors that are not declared as blue, but are, nevertheless, purely blue. These colors are accidentally blue:

  // different result for accidental blues
  scala> printColor(new Color(0, 0, 10))
  R: 0, G: 0, B: 10
  ; all blues equal
  user=> (color-string (struct color 0 0 10))
  "Blue: 10"

The Scala example was written to dispatch based on type, so it treats accidentally blue colors different from "real" Blues. The Clojure example, on the other hand, dispatches based on the actual color values, so all solid blues are treated the same, no matter how they are created.

Of course, nothing stops me from "fixing" the Scala example, e.g. by dispatching on something other than type:

  case class Color(val red:Int, val green:Int, val blue:Int)

  object ColorDemo {
    def colorString(c:Color) = c match {
      case Color(r,0,0) => "Red: " + r
      case Color(0,g,0) => "Green: " + g
      case Color(0,0,b) => "Blue: " + b

    case col:Color => {
      "R: " + col.red + ", " +
      "G: " + col.green + ", " +
      "B: " + col.blue
    }

    case null => "Invalid color"
      case null => "Invalid color"
    }
  }

Or, I could "break" the Clojure example by adding a type tag, and dispatching on that instead. Rich Hickey posted this example on the Clojure mailing list:

  (defstruct color :red :green :blue)

  (defn color-class [name r g b]
   (assoc (struct color r g b) :tag name))

  (defn red [v] (color-class :red  v 0 0))
  (defn green [v] (color-class :green 0 v 0))
  (defn blue [v] (color-class :blue 0 0 v))
  (defmulti color-string :tag)
  (defmethod color-string :red [c] (str "Red: " (:red c)))
  (defmethod color-string :green [c] (str "Green: " (:green c)))
  (defmethod color-string :blue [c] (str "Blue: " (:blue c)))
  (defmethod color-string :default [{:keys [red green blue]}]
     (str "Color, R: " red ", G: " green ", B: " blue)) 

This version now works like the original Scala version, treating "accidental" blue differently from things marked with a :tag of :blue.

Note that multimethods are open. I can add new colors later without having to modify the existing code:

  (defn orange [r g] (color-class :orange r g 0))
  (defmethod color-string :orange [{:keys [red green]}]
     (str "Orange, R: " red ", G: " green)) 

Dynamic Scala?

If you are a dynamic language programmer fearing the tyranny of the Scala compiler, pattern matching is a cause for rejoicing. With pattern matching, you can bypass static typing and get the flexibility of much more dynamic dispatch. Consider: Scala's pattern matching can be used to dispatch on arbitrary predicates. These predicates are not limited to type relationships known at compile time, so a Scala program that uses pattern matching as the cornerstone of its dispatch strategy can be as dynamic as an extremely dynamic Ruby program. Put another way: Scala's catch-all match default (_) is the moral equivalent of Ruby's method_missing.

Conclusions

Dispatch takes many forms. Single dispatch, switch statements, pattern matching, and multiple dispatch all meet similar needs: Selecting runtime behavior in response to varying runtime conditions.

Flexible dispatch is a key element of Java.next. All of the Java.next languages support dispatch strategies that are far more flexible than Java's single dispatch. These strategies are not perfectly interchangeable, but have a great degree of overlap. For example, Clojure's multimethods and Scala's pattern matching look quite different on the surface but can be used to solve similar problems.

Dispatch can be based on criteria more dynamic than the type system, even in Scala.


Notes

  • This article is based on the JVM Language Shootout talk. Check the schedule for a talk near you.
  • Thanks to Ola Bini, Justin Gehtland, Jason Rudolph, Daniel Spiewak, Venkat Subramaniam, and Greg Vaughn for their feedback on a draft of this article.
  • Thanks to Chouser and Rich Hickey for feedback on the Clojure examples.
  • Feedback on how to improve these examples is most welcome!

Revision History

  • 2008/08/29. Fixed fencepost error in Groovy code (Thanks Scott!). How irritating -- I have working unit tests for all the code and get burned by copy and paste.
  • 2008/08/30. Better Scala pattern match in second example, per Stefan's suggestion.

Aug 26 2008

Comments

Java.next Presentation #3: Dispatch

Dispatch takes many forms. Single dispatch, switch statements, pattern matching, and multiple dispatch all meet similar needs: Selecting runtime behavior in response to varying runtime conditions.

Flexible dispatch is a key element of Java.next. All of the Java.next languages support dispatch strategies that are far more flexible than Java's single dispatch.

In this talk (Part 3 of the Java.next series), I will explore how the Java.next languages (Clojure, Groovy, JRuby, and Scala) support dispatch. For more information, see the Java.next Dispatch article on the Relevance blog.

Aug 12 2008

Comments

Java.next #2: Java Interop

This is Part Two of a series of articles on Java.next. In Part Two, I will look at how Java.next languages interoperate with Java.

Java interop is trivial in all of the Java.next languages. We have Java itself to thank for this--the Java Virtual Machine Specification makes it easy for other languages to reflect against and call Java code.

A Swing example

As a first example, consider calling into the Java Swing API to create an application [1] that has

  • a frame
  • button
  • a button handler that responds with a model dialog

For starters, here is the application in plain old Java:

  //java
  import javax.swing.JFrame;
  import javax.swing.JButton;
  import javax.swing.JOptionPane;
  import java.awt.event.ActionListener;
  import java.awt.event.ActionEvent;

  public class Swing {
    public static void main(String[] args) {
      JFrame frame = new JFrame("Hello Swing");
      JButton button = new JButton("Click Me");

      button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
          JOptionPane.showMessageDialog(null,
              String.format("<html>Hello from <b>Java</b><br/>" +
                            "Button %s pressed", event.getActionCommand()));
        }
      });
      frame.getContentPane().add(button);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setVisible(true);
    }
  }

Below, I will present the same Swing application, ported to the Java.next languages. Please take note of two things about these examples:

  • For this post, I am presenting the languages in order of increasing syntactic distance from Java. This makes sense for porting a simple example from the well-known to the increasingly unfamiliar.
  • The ports below are not best practice in the Java.next languages. They are deliberately simplistic, so that I can focus on Java interop. In later installments of this series I will show more idiomatic Java.next code.

Groovy Swing example

Groovy is the Java.next language that looks most like Java. Here is the same example in Groovy:

  //groovy
  import javax.swing.JFrame
  import javax.swing.JButton
  import javax.swing.JOptionPane
  import java.awt.event.ActionListener

  frame = new JFrame("Hello Swing")
  button = new JButton("Click Me")

  button.addActionListener({
    JOptionPane.showMessageDialog(null, """<html>Hello from <b>Groovy</b>
  Button ${it.actionCommand} pressed""")
  } as ActionListener) 
  frame.contentPane.add button

  frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
  frame.pack()
  frame.visible = true

If you compare this to the Java example, it is almost the same code, minus a bunch of unnecessary ceremony. The Groovy version lets us omit:

  • semicolons
  • type declarations
  • most parentheses
  • get and set for property access

The most important benefit, however, comes in the action listener. The Groovy version sports

  • a multiline string (delimited by """)
  • string interpolation of it.actionCommand (inside ${})
  • no need to write an anonymous inner class, simply pass an anonymous function

For a more idiomatic approach to Swing in Groovy, see the Groovy SwingBuilder project.

Since this post is about Java interop I will state the obvious: From Groovy, Java interop is entirely trivial.

Scala Swing example

Next, let's look at the Scala version:

  // Scala (almost right, see below)
  import javax.swing._
  import java.awt.event.{ActionEvent, ActionListener}

  object HelloWorld extends JFrame("Hello Swing") {
    def showButtonMessage(msg: String)  =
      JOptionPane.showMessageDialog(null, String.format("""<html>Hello from <b>Scala</b>. Button %s pressed""", Array(msg)));

    def main(args: Array[String]) {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
      val button = new JButton("Click Me")
      button.addActionListener((e:ActionEvent) => showButtonMessage(e.getActionCommand.toString))
      getContentPane add button
      pack
      setVisible(true)
    }
  }     

The Scala version offers many of the same advantages over Java that the Groovy version provided:

  • fewer type declarations than Java
  • fewer semicolons
  • fewer parentheses

We also see a few items unique to Scala:

  • In Scala, the import wildcard is _, not *. In Scala, * is a valid identifier. (Scala's punctuation-friendly identifiers will be a big advantage later when I am writing DSLs.)
  • Scala has an inline syntax for importing multiple classes in a package.
  • Since we only need one, we declare an object instead of a class.
  • Our object extends JFrame, and Scala lets us call the JFrame constructor inline, instead of having to declare a separate constructor.

Again, the most important differences are in the action listener. Like Groovy, Scala lets us skip the anonymous inner class ritual, and simply pass a function:

  button.addActionListener((e:ActionEvent) => 
    showButtonMessage(e.getActionCommand.toString))

That looks great, except I cheated a little. Scala's implementation of strong typing won't automatically coerce a function into an ActionListener, so the above code won't compile out of the box. Fortunately, Scala's implicit conversions let us have our cake and eat it too: strong typing plus much of the syntactic convenience of a looser type system. All we have to do is tell Scala the the conversion is legal:

  // Yes, we can
  implicit def actionPerformedWrapper(func: (ActionEvent) => Unit) = 
    new ActionListener { def actionPerformed(e:ActionEvent) = func(e) }

With this one-time setup in place, we can now pass a function where an ActionListener is expected.

There seem to be several projects to wrap Swing in more idiomatic Scala. Using one of these libraries you should be able to get a syntax cleaner than the sample code here. See ScalaGUI for one example.

From Scala, Java interop is trivial.

JRuby Swing example

Let's see how JRuby fares:

  include Java
  import javax.swing.JFrame
  import javax.swing.JButton
  import javax.swing.JOptionPane
  import java.awt.event.ActionListener

  button = JButton.new "Click Me"
  button.add_action_listener do |evt|
    JOptionPane.showMessageDialog(nil, <<-END)
  <html>Hello from <b>JRuby</b>.
  Button '#{evt.getActionCommand()}' clicked.
  END
  end

  frame = JFrame.new "Hello Swing"
  frame.content_pane.add button
  frame.default_close_operation = JFrame::EXIT_ON_CLOSE
  frame.pack
  frame.visible = true

If you compare this to the earlier Groovy example, you will see almost exactly the same feature set:

  • fewer type declarations
  • fewer semicolons
  • fewer parentheses
  • simplified property access (no get or set)
  • a multiline string (delimited by END)
  • string interpolation of evt.getActionCommand (the stuff inside #{})

The action listener callback is simplified in a fashion similar to the Groovy example. Ruby automatically generates the ActionListener from a block:

  button.add_action_listener { |evt|
    # do stuff
  }

In the JRuby example I used Ruby conventions for method names, even on Java objects:

  # Ruby
  frame.content_pane

Java programmers expect camel case. As a convenience, JRuby supports both naming conventions:

  # Groovy, Scala, or JRuby
  frame.contentPane

Ruby's flexibility has encouraged a lot of experimentation with alternate syntaxes for Java interop. See JRUBY-903 for some of the history. For a more idiomatic approach to Swing in JRuby, see the Profligacy project.

From JRuby, Java interop is trivial.

Clojure Swing example

Here is the Clojure version:

  ; Clojure 
  ; Clojure
  (import '(javax.swing JFrame JButton JOptionPane))
  (import '(java.awt.event ActionListener))

  (let [frame (JFrame. "Hello Swing")
       button (JButton. "Click Me")]
   (.addActionListener button
     (proxy [ActionListener] []
       (actionPerformed [evt]
         (JOptionPane/showMessageDialog  nil,
            (str "<html>Hello from <b>Clojure</b>. Button "
                 (.getActionCommand evt) " clicked.")))))

   (.. frame getContentPane (add button))
   (doto frame
     (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
     .pack
     (.setVisible true)))

Because Clojure is a Lisp, the syntax is radically different from the others. This deserves hours of discussion, or none. Since my focus here is on Java interop, I am going to save The Great Parenthesis Debate for a later entry in this series. For now, let us suspend judgment on syntax, and focus exclusively on the Java interop.

Importing Java classes is easy. import takes a list. The first element of the list is a package, and the remaining elements are classes to add to the current namespace. Note that this allows the import of multiple classes in a single line.

  (import '(javax.swing JFrame JButton JOptionPane))

Creating a Java instance is easy. Use the (class. &args) form.

  (JFrame. "Hello Swing")

There are multiple ways to call methods on a Java class. If you want to call a single method, you can use the (.methodName obj &args) form. For static calls, you can also use the (class/method &args) form:

  (JOptionPane/showMessageDialog nil "A message") 

Sometimes you want to chain multiple calls together. Where in Java you would say x.y().z(), in Clojure you can use the (.. x (y) (z)) form.

  (.. frame (getContentPane) (add button))

The last three method calls in our example are all on the same frame object. With Clojure's doto form, you can perform multiple operations on an object without having to repeat the object each time.

  (doto frame
    (setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
    pack
    (setVisible true)))

As with the other examples, the action listener is the most interesting part. In Clojure, proxy will dynamically create a Java instance [2], allowing you to implement interfaces and methods as needed.

  (proxy [ActionListener] []
    (actionPerformed [evt] {do stuff here...}))

As with JRuby, this solution is more general, and requires more syntax, than the Groovy approach. Also as with JRuby, you can easily roll your own syntax.

From Clojure, Java interop is trivial.

Try this at home

The interop story in Java.next is almost boring: It Just Works. So to spice things up a little, here is an exercise in rolling your own constructs, inspired by the examples above. Consider Clojure's import, which can import multiple Java classes in a single line of code.

  (import '(javax.swing JFrame JButton JOptionPane))

Why can't this be even more general? Try your hand at writing a custom import function in one of the Java.next languages. Some useful features might be

  • import all the classes in a JAR
  • import all the classes in the intersection of a package and a JAR
  • import only interfaces
  • import all classes matching some criteria
  • import all classes except those matching some criteria

Let me know what you come up with, and I will link to it here.

Conclusion

In the examples above, I have demonstrated how all of the Java.next libraries can trivially interoperate with Java. Each of examples called the Swing library with fewer lines of code than the Java version. More importantly, the Java.next versions capture the essence of the program with less ceremony.

Seamless interoperation with Java should not be the primary yardstick when measuring Java.next languages, because they all get it right. There are complexities and corner cases beyond what I have shown here, in all of the Java.next languages. But I consider the Java interop problem to be basically solved.

In these first two articles, I have stayed fairly close to Java style while demonstrating Java.next language features. With that groundwork in place, it is time to start using idiomatic Java.next. In the next installment of the Java.next series, we will look at how the Java.next languages support Domain-Specific Languages.


Notes

  • This series is taken from the JVM Language Shootout talk. Check the schedule for a talk near you.
  • Suggestions for improving the code samples above are most welcome.
  • Thanks to Jason Rudolph, Glenn Vanderburg, and Greg Vaughn for reading an earlier draft of this article.

Footnotes

  1. I took the Swing application example from the JRuby samples, and ported it to the other Java.next languages.
  2. Clojure's proxy creates classes as necessary behind the scenes. In Java.next, the dichotomy of class and object is not constantly center stage.

Revisions

  • 2008/08/14. Updated Clojure example and prose per Rich Hickey's suggestion. Updated Groovy example to include pointer to SwingBuilder, per Andres Almiray. Updated JRuby example and prose based on suggestions from Nick Sieger and Ola Bini. Updated Scala example per Tony Morris's suggestion. Thanks for all the improvements!
  • 2009/10/16. Update Clojure example to the modern (dot-requiring) version of doto.

Aug 04 2008

Comments

Java.next: Common Ground

This is Part One of a series of articles on Java.next. In Part One, I will explore the common ground shared by the Java.next languages.

I have chosen four languages which together represent "Java.next": Clojure, Groovy, JRuby, and Scala. At first glance, these languages are wildly different. Clojure is a Lisp. Groovy is the "almost Java" choice. JRuby has the beauty of Ruby, and the mindshare of Rails. Scala, unlike the others, brings the notion that we need more static typing.

As you might imagine, there is heated debate about which of these languages is best for some purpose, or best in general. Lost in the debate is the fact that these languages share a ton of common ground. They all evolved against a shared background, the Java language. Their design decisions are all influenced by what has worked well in Java, and what has failed.

In this article I will demonstrate two important points about the common ground these languages share:

  • Over the last decade of coding in object-oriented, VM-based languages, we have learned a lot about writing expressive, maintainable applications. Java.next incorporates this knowledge, enabling essence over ceremony.
  • The "essence vs. ceremony" design choices add up to a very different way of programming. The mental shift from Java to Java.next is a bigger shift than the previous shift from C/C++ to Java.

I have distilled the shared advantages of Java.next to eight points, which are explored in more detail below.

  • everything is an object
  • low-ceremony property definitions
  • expressive collections
  • functional programming
  • overriding operators
  • maintainable exception handling
  • adding methods to existing objects
  • roll-your-own constructs

Everything is an object

In Java, we live every day with the distinction between objects and primitives. This causes three practical problems:

  1. APIs must be duplicated: one method for objects, and another for primitives. Or worse, septlicated. One method for objects, and one each for different primitive types.
  2. The default (efficient, easy-to-use) numeric types have range limitations. Exceed them and your program breaks in mysterious ways.
  3. You cannot use intuitive math operators (+,-,etc.) with accurate numeric types.

In Java.next, everything is an object. You can invoke methods on all types using the same syntax.

  ; clojure
  (. 1 floatValue)
  1.0

  // groovy
  1.floatValue()
  ===> 1.0

  # ruby
  1.to_f
  => 1.0

  // scala
  1.floatValue
  res1: Float = 1.0

Low-ceremony property definitions

In Java, to create a property, you must define a field, a getter, a setter, and (often) a constructor, all with appropriate protection modifiers. In Java.next, you can define all of these in a single step.

  ; clojure
  (defstruct person :first-name :last-name)

  // groovy
  class Person {
      def firstName
      def lastName
  }

    # ruby
    Person = Struct.new(:first_name, :last_name)

    // scala
    case class Person(firstName: String, lastName: String) {}

If you need to override (or omit) a getter, setter, or constructor for a class, you can also do that, without having to spell out all boilerplate versions of the other pieces.

And that's not all. All of these languages embrace TMTOWTDI (There's More Than One Way To Do It), so there are multiple variants on the approaches shown above.

Expressive collections

Java.next provides a convenient literal syntax for the most important collections: arrays and maps. In addition, you can string together multiple operations by passing function arguments, without having to write explicit iterators or loops. For example, to find the all the squares under 100 that are also odd:

  ; clojure
  (filter (fn [x] (= 1 (rem x 2))) (map (fn [x] (* x x)) (range 10)))
  (1 9 25 49 81)

  // groovy
  (1..10).collect{ it*it }.findAll { it%2 == 1}
  ===> [1, 9, 25, 49, 81]

  # ruby
  (1..10).collect{ |x| x*x }.select{ |x| x%2 == 1}
  => [1, 9, 25, 49, 81]

  // scala
  (1 to 10).map(x => x*x).filter(x => x%2 == 1)
  res20: Seq.Projection[Int] = RangeMF(1, 9, 25, 49, 81)

There are similar conveniences for name/value collections, a.k.a. hashes or dictionaries.

Functional programming

The convenient collections described above are a special case of a more general idea: functional programming. Java.next supports functions as first class objects, allowing function arguments, functions that create new functions, and closures over the current scope. As a simple example, consider creating an adder function that adds some value chosen at runtime:

  ; clojure
  (defn adder [x] (fn [y] (+ x y)))

  // groovy
  adder = { add -> { val -> val + add } } 

  # ruby
  def adder(add)
    lambda { |x| x + add }
  end

  // scala
  def sum(a: Int)(b: Int) = a + b

Overriding operators

In Java, you cannot override operators. Math looks like this, for types like BigDecimal:

  // Java math
  balance.add(balance.multiply(interest));

Java.next allows you to override operators. This allows you to do create new types that feel like built-in types, e.g. you could write a ComplexNumber or RationalNumber that supports +, -, *, and /.

  ; Clojure
  (+ balance (* balance interest))

  // Groovy
  balance + (balance * interest)

  # JRuby
  balance + (balance * interest)

  // Scala (See [1])
  balance + (balance * interest)

Maintainable exception handling

Checked exceptions are a failed experiment. Java code is bloated with checked exception handling code that tends to obscure intent without improving error handling. Worse yet, checked exceptions are a maintenance headache at abstraction boundaries. (New kinds of unrecoverable failures down the dependency chain should not necessitate recompilation!)

Java.next does not require you to declare checked exceptions, or to explicitly deal with checked exceptions from other code. It is a testimony to the power of Java (the platform) that other languages are free to ignore the ugliness of checked exceptions in Java (the language).

Adding methods to existing types

In Java, you cannot add methods to existing types. This leads to absurd object-mismodeling, as developers create utility classes that defy the point of OO:

  // Java (from the Jakarta Commons)
  public class StringUtils { 
    public static boolean isBlank(String str) { 
    int strLen; 
    if (str == null || (strLen = str.length()) == 0) { 
      return true; 
    }  
    for (int i = 0; i < strLen; i++) { 
        if ((Character.isWhitespace(str.charAt(i)) == false)) { 
          return false; 
        } 
    }
  }

In Java.next, you can add methods to existing types:

  ; Clojure
  (defmulti blank? class)
  (defmethod blank? String [s] (every? #{\space} s))
  (defmethod blank? nil [_] true)

  // Groovy
  String.metaClass.isBlank = {
    length() == 0 || every { Character.isWhitespace(it.charAt(0)) }
  }

  # Ruby (from Rails)
  class String 
    def blank? 
        empty? || strip.empty? 
    end 
  end 

  // Scala
  class CharWrapper(ch: Char) {
    def isWhitespace = Character.isWhitespace(ch)
  }
  implicit def charWrapper(ch: Character) = new CharWrapper(ch)
  class BlankWrapper(s: String) {
    def isBlank = s.isEmpty || s.forall(ch => ch.isWhitespace)
  }
  implicit def stringWrapper(s: String) = new BlankWrapper(s)

Roll-your-own constructs

In Java, you have the language and the libraries. The two are clearly distinct: you can write new libraries, but you cannot add language features.

In Java.next, the line between language and libraries is blurry. You can create new constructs that work like core language features. For example, Clojure provides an and function.

; clojure
(and 1 2) => 2

But maybe your problem domain isn't so binary. You need a most function, that returns true if most of its arguments evaluate to true. Clojure doesn't have this, but you can write one:

  ; clojure
  (most 1 2) => true
  (most 1 2 nil) => true
  (most 1 nil nil) => false

The point here is not "Does my language need a 'most' conditional?" Probably not. The point is that different domains have different needs. In Java.next, the boundary between the language and the libraries is a minimized. You can adapt the language to your domain, instead of the other way around.

As another example, consider Ruby's attribute syntax:

  # Ruby
  class Account
    attr_accessor :name
    dsl_attribute :type
  end

attr_accessor is built into the language. dsl_attribute is a library method that I wrote, which allows you to omit the "=" when assigning values, e.g.

  # normal attributes
  account.name = "foo"

  # equals-free attributes
  account.type checking

Conclusions

The Java.next languages share a ton of common ground. Although I've used small isolated examples for explanation, the real power comes from using these features together. Combining all the Java.next features leads to an entirely different style of coding.

  • You do not have to code defensively, using a slew of factories, patterns, and dependency injection to keep your code testable and adaptable. Instead, you can build a minimal solution and evolve it.
  • Instead of coding in your Java.next language, you can develop internal Domain-Specific Languages (DSLs) that better match your problem domain.

In my experience, this style of coding tends to reduce the size of a codebase by an order of magnitude, while improving readability.

Many people are looking for the "next big language." The next big language is already here, but it isn't a single language. It is the collection of ideas above (plus probably some I missed) as manifested in Java.next.

Does the transition to Java.next deserve the name "big"? Absolutely. In my experience, the move from Java to Java.next is every bit as big as the previous tectonic shifts in the industry, both in learning curve and in productivity advantages once you make the transition.

As an industry, we need to reset the bar to include Java.next. Once we have, we can have a conversation about the differences in these languages. I will take up the unique aspects of the Java.next languages in future installments of this series.


Notes

  • This article is taken from the first half of the JVM Language Shootout talk that I wrote for NFJS. Check the schedule for a talk near you.
  • Suggestions for improving the code samples above are most welcome.
  • Thanks to Justin Gehtland, Jason Rudolph, Rob Sanheim, Glenn Vanderburg, and Greg Vaughn for reading an earlier draft of this article.

Footnotes

  1. The BigDecimal example does not work as I would expect on the Scala build I have (2.7.1.final). But the important point is that I could make it work by adding an implicit conversion. I am not dependent on the language designers, I can improve the language myself.

Revisions

  • 2008/08/04: fixed errata, better Clojure example for expressive collections.
  • 2008/08/12: added Rich Hickey's improved blank? example for Clojure.

Popular Tags