Posted by Administrator on the 8th of December, 2008 at 2:41 pm under Java and Technical.    This post has 2 comments.

After warning someone about the problems of double checked locking I discovered it’s been fixed in Java 5. Simply add the volatile keyword and it’s all good.

See Wikipedia for all the details.

Posted by Administrator on the 5th of May, 2008 at 2:15 pm under Java.    This post has one comment.

I think my favourite blog at the moment would be Charles Nutter’s. You can always count on him for enthusiastic informative postings. It isn’t hard to tell he loves his job - it comes through very strongly in his posts. His last post was a pearler. In it he talks about call site optimizations and the massive improvements they have made in the current Groovy 1.6 beta builds.

As I’ve posted in the past I’ve been impressed by the flexibility of Groovy. In spite of this I’ve been reluctant to recommend it for anything particularly heavy duty as it’s really way too slow. I expect a language as dynamic as Groovy to be slow however Groovy 1.5 is _very_ _very_ slow so it’s great to read about some the improvements in this area. I’m sure Groovy will never be a speed demon, it was never made for that - but if they get can to the level of being _fast enough_ then that will be awesome.

One thing his post has done for me has shown that the Java virtual machine has got real promise. Perhaps one day Java will no longer be the primary language we use to access the JVM. Perhaps one day it will be the platform that gets all attention regardless of whether it is JRuby, Python or Groovy we use do the actual programming. Either way the Java HotSpot compiler is an amazing piece of technology that I’m sure will continue to have a strong future.

Posted by Administrator on the 18th of April, 2008 at 10:27 am under Java.    This post has one comment.

Charles Nutter is in on the fun with a Ruby version:


def subn(n, list)
    return [[]] if n == 0
    return [] if list.empty?

    remainder = list[1..-1]
    subn(n-1, remainder).collect {|it| [list[ 0 ]] + it } + subn(n, remainder)
end

That made me realise there was some further things I could do to cut things down although realistically I don’t think you gain much at this point:


def subn(n, list) {
    if (n == 0) return [[]]
    if (list.empty) return []

    def remainder = list.subList(1, list.size())
    subn(n-1, remainder).collect { [list[ 0 ]] + it } + subn(n, remainder)
}

As with the Ruby version I’ve removed the semicolons and the return statement at the end. I would have liked to use the 1..-1 array range to get the remainder but could not. Groovy supports this however there is a slight difference between list.subList(1, list.size()) and 1..-1 in Groovy. In Ruby this does not seem to be the case.

Take the following:


a = [1, 2, 3]
b = a[1..-1]

In Groovy b will be [2, 3] as expected. If however our array is only 1 element long as follows:


a = [1]
b = a[1..-1]

We get an error:

Caught: java.lang.IndexOutOfBoundsException: toIndex = 2

So what’s going on here? Well, if I understand correctly our range is being mapped to 1..0 at runtime which is not really what we want. I’m told on the mailing list that 1.5.5 and 1.6 has included the methods list.head() and list.tail(). This should mean we can do something like:


def subn(n, list) {
    if (n == 0) return [[]]
    if (list.empty) return []

    subn(n-1, list.tail()).collect { [list.head()] + it } + subn(n, list.tail())
}

Obviously Ruby array indexing is resolved differently from Groovy.

Posted by Administrator on the 17th of April, 2008 at 4:30 pm under Java.    This post has 4 comments.

I came across a post on (cadr life) the other day about creating a function to find all subsequences of a list with a certain length. The Java version was particularly icky and in his post he shows the equivalent code in a couple of languages. I thought it might be interesting to try it in Groovy so I fired up Intellij Idea and pasted the Java version in.


private static < T > List< List< T >> subn(int n, List< T > li) {
  List< List< T > > ret = new ArrayList< List< T >>();
  if (n == 0) {
      ret.add(new ArrayList< T >());
      return ret;
  }
  if (li.isEmpty()) {
      return ret;
  }
  T x = li.get(0);
  List< T> xs = li.subList(1, li.size());
  for (List< T> sub : subn(n-1, xs)) {
      sub.add(0, x);
      ret.add(sub);
  }
  ret.addAll(subn(n, xs));
  return ret;
}

Because Groovy is so close syntactically I was able to paste this in as is and run it without modification.

For my first step I thought I’d remove the static typing. I’m not against statically typed code but for such a small self contained function I’m not sure it adds much.


def subn(n, li) {
    def ret = new ArrayList();
    if (n == 0) {
        ret.add(new ArrayList());
        return ret;
    }
    if (li.isEmpty()) {
        return ret;
    }
    def x = li.get(0);
    def xs = li.subList(1, li.size());
    for (sub in subn(n-1, xs)) {
        sub.add(0, x);
        ret.add(sub);
    }
    ret.addAll(subn(n, xs));
    return ret;
}

While this reduces character count it doesn’t change the structure at all. At best it’s very slightly clearer than the original.

Next step was to use array literals:


def subn(n, li) {
    def ret = [];
    if (n == 0) {
        ret.add([]);
        return ret;
    }
    if (li.isEmpty()) {
        return ret;
    }
    def x = li.get(0);
    def xs = li.subList(1, li.size());
    for (sub in subn(n-1, xs)) {
        sub.add(0, x);
        ret.add(sub);
    }
    ret.addAll(subn(n, xs));
    return ret;
}

Nice, some more characters trimmed. By simplifying the if statements we can cut back a bit more:


def subn(n, li) {
    if (n == 0) return [[]];
    if (li.isEmpty()) return [];

    def ret = [];
    def x = li.get(0);
    def xs = li.subList(1, li.size());
    for (sub in subn(n-1, xs)) {
        sub.add(0, x);
        ret.add(sub);
    }
    ret.addAll(subn(n, xs));
    return ret;
}

I’m not really a fan of short variable names so next step is to rename some variables. In addition to this I’ll change the loop slightly to use the each function. The ‘it’ magic variable replaces the ’sub’ variable.


def subn(n, list) {
    if (n == 0) return [[]];
    if (list.isEmpty()) return [];

    def ret = [];
    def head = list.get(0);
    def remainder = list.subList(1, list.size());

    subn(n-1, remainder).each {
        it.add(0, head);
        ret.add(it);
    }
    ret.addAll(subn(n, remainder));
    return ret;
}

By adding the collections together we can simplify the loop a bit more:


def subn(n, list) {
    if (n == 0) return [[]];
    if (list.isEmpty()) return [];

    def ret = [];
    def head = list.get(0);
    def remainder = list.subList(1, list.size());

    subn(n-1, remainder).each {
        ret.add([head] + it);
    }
    ret.addAll(subn(n, remainder));
    return ret;
}

Looking at the code it becomes clear that the ‘ret’ variable is just accumulating the results. We can use the collect method for this purpose instead.


def subn(n, list) {
    if (n == 0) return [[]];
    if (list.isEmpty()) return [];

    def head = list.get(0);
    def remainder = list.subList(1, list.size());

    def ret = subn(n-1, remainder).collect { [head] + it }
    ret.addAll(subn(n, remainder));
    return ret;
}

In fact we really don’t need ‘ret’ at all if instead we just add the two collections together:


def subn(n, list) {
    if (n == 0) return [[]];
    if (list.isEmpty()) return [];

    def head = list.get(0);
    def remainder = list.subList(1, list.size());

    return subn(n-1, remainder).collect { [head] + it } + subn(n, remainder);
}

Finally lets inline the head variable. It’s only used in one place anyway so not really worth keeping it. In addition we’ll use Groovy list indexing to remove the get() call.


def subn(n, list) {
    if (n == 0) return [[]];
    if (list.isEmpty()) return [];

    def remainder = list.subList(1, list.size());
    return subn(n-1, remainder).collect { [list[ 0 ]] + it } + subn(n, remainder);
}

Simple. In my opinion this is much clearer than the original and we managed it by making small incremental changes from the Java version.

A lot of the clarity comes from the fact that we have closures. In fact in his next post Ray posted an example using the Java BGGA closure proposal. Here it is reproduced below:


import static com.cadrlife.ListUtils.*;
...
private static < T > List< List< T >> subn(int n, List< T > list) {
    if (n == 0) {
        return Collections.< List< T >>singletonList(new ArrayList< T >());
    }
    if (list.isEmpty()) {
        return new ArrayList< List< T >>();
    }
    T first = list.get(0);
    List< T > rest = list.subList(1, list.size());
    return addAll(collect(subn(n-1, rest), {List< T > sub => push(first, sub)}),
                  subn(n, rest));
}

While this is a big improvement from the original it is still clouded by a lot of syntax noise IMHO. Either way I’m very keen for closures to make it into the language.

Update: Fixed the formatting. I wish wordpress was a bit nicer with pasted in source code

Posted by Administrator on the 19th of March, 2008 at 12:56 pm under Java and Technical.    This post has 3 comments.

I like to think I’m reasonably up-to-date with Java technologies but then I discovered something today that shows up that I’m still ignorant of a lot of available technology that’s out there. Today I ran across hamcrest which is now apparently part of junit 4.4 and above.

Basically it replaces the old assertEquals() & variants with an assertThat statement. ie:


assertThat([value], [matcher statement]);

Some examples:


assertThat(x, is(3));
assertThat(x, is(not(4)));
assertThat(responseString, either(containsString("color")).or(containsString("colour")));
assertThat(myList, hasItem("3"));

Basically all sorts of matchers are possible. The advantages here are improved failure reporting and a clearer expression of intent.

There’s some other interesting stuff built around this too - such as hamcrest collections. Take a look at this:


smiths = select(people, where(Person.class).getLastName(), equalToIgnoringCase("smith"));

Looks like good stuff to play around with over the next few days.

Posted by Administrator on the 26th of February, 2008 at 10:17 am under Java and Technical.    This post has no comments.

After being initially interested in Groovy I cooled on it as a language and haven’t touched it in some time. Recently I had need to create a little throwaway program and gave Groovy another go.

Groovy is now up to version 1.5 and Grails which is heavily inspired by Ruby on Rails has recently release their 1.0 version. As a programming platform it’s matured a fair amount since I first looked at it. One of the reasons I chose to give it a go it that it has good support in my IDE of choice - IntelliJ Idea. The Groovy/Grails plugin while still a little rough around the edges does a good job of getting you going with Groovy quickly. So far I haven’t had the chance to play with Grails yet so I can’t comment on how well that works.

One of the things you notice straight away when working with Groovy is how easy it is for a Java programmer to get into the language. Groovy syntax looks very similar to Java and in many cases you can paste Java code in and it will work. Obviously though if you’re pasting Java code into a Groovy file you’re not really utilising the full potential of the language. The main point of Groovy as far as I can tell is to address some of the pain points in Java.

Groovy like the upcoming ECMAScript 4 lets you optionally type variables. I like this trend in language design. It lets me decide when typing is important to me and to let me ignore it when it’s not.

The project I was writing involved scraping some info from a web page and doing some manipulation of the data. One of the big noticeable improvements I noticed very quickly was the ease at which collections are managed. Collection manipulation in Java is positively frustrating in comparison. Ranges/closures/high order functions/collection literals all help immensely here.

Another big help was the oddly named XMLSlurper. This lets you navigate DOM structures very simply. Just take a look at XMLSlurper documentation page for a good feel for how easy DOM manipulation can become.

Of course to work with XMLSlurper I had to convert the HTML into XML and for this I used a Java library called tagsoup. This is where the integration between Java and Groovy shines through as there is very little impedance mismatch between the two languages since they both ultimately inherit from java.lang.Object.

Overall it was a pleasant experience using Groovy and I’d love to do a larger project with it in the future.

Posted by Administrator on the 13th of February, 2008 at 9:32 am under Java and Technical.    This post has no comments.

Having needed to so some parsing recently I picked up a copy of The Definitive ANTLR Reference: Building Domain-Specific Languages from The Pragmatic Bookshelf. I’ve found myself purchasing a lot of their books recently. The PDF versions are great in particular because they come with no nasty DRM and are genuinely cheaper than the dead tree equivalent.

The book itself weighs in at a reasonable 358 pages. I attempted to initially learn all about ANTLR 3 from the website. Unfortunately like many open source projects the online documentation is somewhat lacking. I think sometimes that people think that if they put up a wiki then everything magically becomes organized. While I’ve seen good examples of wiki based sites it is usually because someone has put in a lot of time and trouble to structure it well.

In any case I usually don’t mind shelling out a little money to purchase a book. In this case I’m pretty happy with the book itself. The sometimes complicated subject of parsing is covered in a good amount of detail. Someone wishing to skim the subject and get going quickly will be well served by reading through the first few chapters in the book.

Strangely after an introduction to the subject the book jumps directly into the reference material. Most books I’ve seen actually put this sort of material at the end. I’m not sure why Terence chose to put this right after the introductory chapters. Regardless you’re always free to skim over this section. Be careful however… by chapter 8 (Tree Construction) the material becomes decidedly less referencey so don’t skim the reference section completely.

The final section of the book covers the more difficult material such as exactly what LL(*) does for you, how to use semantic and syntactic predicates to solve parsing conflicts and a good amount of detail in backtracking and memoization.

Certainly you can’t go too far wrong by purchasing this book although very little of the book directly talks about domain specific languages. I think that is in there more for marketing reasons which I personally find somewhat annoying.

The book also gives very little time to covering generating parsers in languages other than Java even though the tool is supposed to be capable of this. I find this somewhat strange however I’m sure it wouldn’t be hard to figure this out without help from the book.

ANTLR itself is a great tool. The subject matter is initially intimidating but in practice it isn’t hard at all to get a working parser going. The ANTLR-works tool that ships with v3 is simply amazing and makes building a grammar really easy. Recommended to anyone wanting to build a parser.

Posted by Administrator on the 22nd of August, 2007 at 11:25 am under Java.    This post has one comment.

In the past I’ve been a proponent of Tapestry. It had a nice component based view of the world and there were certain elegant concepts that were very appealing. Unfortunately it had two major flaws:

1. It’s too complicated.
2. Backward compatibility has been thrown out the door multiple times.

Tapestry takes a significant time to learn. Although getting basic stuff done with Tapestry isn’t too hard, and it does get easier with each release, the more advanced stuff can be confusing. There’s a lot of code under the hood. It is my belief that you can’t have that much code without things getting complicated.

The backward compatibility issue is also a big problem. Every release of Tapestry has changed some fundamental thing about the way the framework works. If you’ve got a substantial investment in code based around a version of Tapestry that gets obsoleted within 6 months then obsoleted again in another year it doesn’t do wonders for your confidence in the project. No project exists in a vacuum. There are external things to consider such as tools, projects and books. These all suffer when the foundations of a framework keep shifting.

There was a great discussion around these issues in the Tapestry 101 weblog. To be fair it should be pointed out that Howard has said the next version of Tapestry should be the last major release. I hope this is true because I still think Tapestry has a lot going for it.

Anyway… didn’t actually want to rant on Tapestry. The frameworks I have been using these days is not one that many are aware of. The Click Framework is yet another component based framework.

One of the goals of click is to be very simple, easy to learn and not try to do everything under the sun. I think it meets these goals very well. If you don’t count the click controls the total size of the click framework is under 20 classes. The API has also proved to be be very stable.

Anyone could pick click up very easily. Many frameworks seem to suffer from the problem of layering on massive piles of unnecessary abstraction. When the core framework is very thin it is usually not hard to trace a problem back to it’s root cause.

Making it even simpler to use is some excellent documentation. This is another area where many projects can be found lacking. Overall click is probably the most undervalued web framework around at the moment. The downside to this is that it’s unlikely that you’ll find anyone who has experience with it. While this is certainly an issue I’ve never had anyone who has used it come and say that it’s too hard to pick up. Spending 10 minutes reading the documentation is usually enough to give most people a good idea of how to do the basics.

So if you’re looking around wondering which framework to go with take some time and try Click.

Posted by Administrator on the 25th of June, 2007 at 4:46 pm under Java and Technical.    This post has 3 comments.

I must confess myself disappointed with the latest release of hibernate. What was a reasonably simple project seems to have ballooned into something a lot more complicated. If you go to the website you’ll find 3.2.4.SP1 is listed as the latest release. I was thinking this would be compatible with hibernate annotations 3.3.0 GA however after some frustrating hours trying to get things going I discovered I had to downgrade to hibernate 3.2.2 to get things working. Effectively this means that the latest released version of hibernate is not compatible with any released versions of the annotations project.

Whatever happened to minor point releases just being backward compatible bug fixes? This is the same sort of problem I’ve had with JBoss in the past. Minor version numbers including major backward-incompatible changes.

Posted by Administrator on the 22nd of June, 2007 at 10:03 am under Java, Javascript, Technical and Uncategorized.    This post has no comments.

Increasingly there seems to be a move towards language alternatives that function on the Java (VM) Platform. Personally I think the platform itself is the best thing about Java. The language while adequate has never really particularly inspiring. Certainly when I started coding Java it was a big step up from the horrible VB 3.0 language that was my bread and butter but even at that time it was certainly not the pinnacle of language design.

These days we’re seeing more and more options on the JVM. JRuby, JPython, Scala, Groovy and many other lesser known options. It remains to be seen how well these will be adopted. I suspect JRuby will become more popular as an option for Ruby developers. The IDE support being built into NetBeans will mean great tool support. Tool support is frequently one of the missing options with alternative languages.

These days I’m actually doing more Javascript than Java. Thank goodness for Firebug. Good tools can make all the difference.