Links

  • 1. Sogeti
  • 2. JBoss
  • 3. IBM
  • 4. Oracle
  • 5. SpringSource
  • 6. NL-JUG
  • 7. Java

Archives

Syndication  RSS 2.0

RSS 1.0
RSS 2.0

Bookmark this site

Add 'JCN Blog' site to delicious  Add 'JCN Blog' site to technorati  Add 'JCN Blog' site to digg  Add 'JCN Blog' site to dzone

Posted by Sander van Der Waal at 1:16 on Tuesday 13 May    Add 'More Effective Java' site to delicious  Add 'More Effective Java' site to technorati  Add 'More Effective Java' site to digg  Add 'More Effective Java' site to dzone

As Erik-Berndt posted earlier, the second edition of Joshua Bloch’s bestseller ‘Effective Java’ is out. The author himself gave a session on the new features in this book on Friday morning. If you already have the book, read items 28 on Generics, 31-34 and 77 on Enum types, and 71 on Lazy initialization. For this blog, I will focus on three specific Enum examples he showed that I think can be useful.

The first one is easiest. Suppose you want to write an enum that contains the number of musicians in different formations.
This is what it may look like:


public enum Ensemble {
  SOLO, DUET, TRIO, QUARTET, QUINTET,
  SEXTET, SEPTET, OCTET, NONET, DECTET;
 
  public int numberOfMusicians()
  {
    // ???
  }
}

Now how do you determine the number of musicians in these ensembles?
At first glance, you could suggest using return ordinal() + 1; to determine the number of musicians.

The problem with this approach is that it is a maintenance nightmare. You cannot add multiple constants with the same integer value, and you get in trouble when you wnat to insert a new type of ensemble that does not have the number of the previous type + 1. Here a better way to do it that solves all the problems mentioned and looks quite elegant:


public enum Ensemble {
  SOLO(1), DUET(2), TRIO(3), QUARTET(4), QUINTET(5),
  SEXTET(6), SEPTET(7), OCTET(8), DOUBLE_QUARTET(8),
  NONET(9), DECTET(10), TRIPLE_QUARTET(12);

  private final int numberOfMusicians;

  Ensemble(int size) {
    numberOfMusicians = size;
  }

  public int numberOfMusicians() {
    return numberOfMusicians;
  }
}

Secondly, enums are a good replacement for the old approach where you used the bits of an integer to represent up to 32 boolean variables, like in this example:


public class Text {
  public static final int STYLE_BOLD = 1;
  public static final int STYLE_ITALIC = 2;
  public static final int STYLE_UNDERLINE = 4;
  public static final int STYLE_STRIKETHROUGH = 8;

  // Param is bitwise OR of 0 or more STYLE_ values
  public void applyStyles(int styles) {
    // ...
  }
}

This type of usage can cause some problems. For example, bit fields are not safe, there are are no namespaces (forcing you to prefix the constant names) and there is no easy way to iterate over the elements. With enums, you get an elegant alternative:


public class Text {
  public enum Style {
    BOLD, ITALIC, UNDERLINE, STRIKETHROUGH
  }

  // Any Set could be passed in, but EnumSet is best
  public void applyStyles(Set<Style> styles) {
    //...
  }
}

As a client using this code, this is an example of how to call this method:text.applyStyles(EnumSet.of(Style.BOLD, Style.ITALIC));

This way, you solve all the problems mentioned. But the best thing is the compiler will optimize your code to the former layout with bit fields, so it won’t ‘cost’ you anything!

Finally, here is an example of how you can model the transitions of one of the three physical phases into another. This code is common, but flawed, according to Bloch:


public enum Phase {
  SOLID, LIQUID, GAS;
 
  public enum Transition {
    MELT, FREEZE, BOIL, CONDENSE, SUBLIME, DEPOSIT;

    // Rows indexed by src-ordinal, cols by dst-ordinal
    private static final Transition[][] TRANSITIONS = {
    { null, MELT, SUBLIME },
    { FREEZE, null, BOIL },
    { DEPOSIT, CONDENSE, null }
  };

  // Returns phase transition from one phase to another
  public static Transition from(Phase src, Phase dst) {
    return TRANSITIONS[src.ordinal()][dst.ordinal()];
  }
}

The problems with this implementation are not too hard to see. It is error-prone: mistakes in the transition table cause runtime failures. Furthermore, you easily mess up the table when adding behavior. Also readibility may become a problem if you have many phases.
According to Joshua Bloch, an EnumMap is the way to go. And I must agree, this code definitely looks a lot better:


public enum Phase {
  SOLID, LIQUID, GAS;
   
  public enum Transition {
    MELT(SOLID, LIQUID), FREEZE(LIQUID, SOLID),
    BOIL(LIQUID, GAS), CONDENSE(GAS, LIQUID),
    SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID);

    private final Phase src;
    private final Phase dst;
   
    Transition(Phase src, Phase dst) {
      this.src = src;
      this.dst = dst;
    }
  }

However, the class gets somewhat more complicated when we take a look at the from-method adding behavior to return the correct transition:


  // Initialize the phase transition map
  private static final Map<Phase, Map<Phase,Transition>> m =
    new EnumMap<Phase, Map<Phase,Transition>>(Phase.class);

  static {
    // Insert empty map for each src state
    for (Phase p : Phase.values())
      m.put(p,new EnumMap<Phase,Transition>(Phase.class));

    // Insert state transitions
    for (Transition trans : Transition.values())
      m.get(trans.src).put(trans.dst, trans);
  }

  public static Transition from(Phase src, Phase dst) {
    return m.get(src).get(dst);
  }
}

But the best thing about this second part is that it is just some administration code that you add once, is initialized once when the class is loaded, and does not need maintenance in case you add data. For instance, if you add support for the PLASMA state, all you have to do is adding the PLASMA constant to Phase, and IONIZE(GAS, PLASMA) plus DEIONIZE(PLASMA, GAS) to Transition, and that's it! The rest can remain untouched.

Much more of these kinds of helpful insights are added in the second edition of Effective Java!

Posted by Sander van Der Waal at 12:31 on Monday 12 May    Add 'Top 10 Patterns for Scaling Out Java Applications' site to delicious  Add 'Top 10 Patterns for Scaling Out Java Applications' site to technorati  Add 'Top 10 Patterns for Scaling Out Java Applications' site to digg  Add 'Top 10 Patterns for Scaling Out Java Applications' site to dzone

An excellent presentation was given by Cameron Purdy of Oracle about scalibility of Java Applications. There was too much interesting information to fit in one post, but I will just try to sum up the highlights following his top 10. Much of it shamelessly ripped from his slides.

Read the rest of this entry »

Posted by Sander van Der Waal at 11:21 on Monday 12 May    Add 'Converting application to OSGi' site to delicious  Add 'Converting application to OSGi' site to technorati  Add 'Converting application to OSGi' site to digg  Add 'Converting application to OSGi' site to dzone

One of the session I personally found the most interesting was the one on converting large applications to OSGi, by OSGi-gurus Peter Kriens and BJ Hargrave. OSGi is a module system for Java and converting an application to OSGi means making your code modular, so dependencies between modules are clear. In this post, I will focus on what is relevant in the discussion of writing modular code for an OSGi system. To not make this post even lengthier than it will be just discussing that, I will not go into the basics of OSGi itself. You could visit http://www.osgi.org for excellent introductions to OSGi or have a look at the articles Neil Bartlett wrote. 

Read the rest of this entry »

Posted by Erik-Berndt Scheper at 18:43 on Saturday 10 May    Add 'Free photo with Duke' site to delicious  Add 'Free photo with Duke' site to technorati  Add 'Free photo with Duke' site to digg  Add 'Free photo with Duke' site to dzone

Since we’re from the Netherlands, we couldn’t resist a free photo with Duke at the JavaOne. I guess that concludes it for us. It’s been a truly wonderful week and I hope at least some of you have read something new or useful in the blogs.

SanderAndErik-BerndtWithDuke

Many thanks,

Erik-Berndt

Posted by Erik-Berndt Scheper at 8:21 on Saturday 10 May    Add 'Effective Java (second edition): book-signing by Joshua Bloch' site to delicious  Add 'Effective Java (second edition): book-signing by Joshua Bloch' site to technorati  Add 'Effective Java (second edition): book-signing by Joshua Bloch' site to digg  Add 'Effective Java (second edition): book-signing by Joshua Bloch' site to dzone

This afternoon, Joshua Bloch has been personally signing copies of Effective Java, as you can see below (mine as well).

JoshuaBlochSignsEffectiveJava

Posted by Erik-Berndt Scheper at 8:15 on Saturday 10 May    Add 'JSR 310: Its high time! A new date and time API' site to delicious  Add 'JSR 310: Its high time! A new date and time API' site to technorati  Add 'JSR 310: Its high time! A new date and time API' site to digg  Add 'JSR 310: Its high time! A new date and time API' site to dzone

As (hopefully) everyone is aware of, the current date and time API’s in Java are seriously flawed. For example:

  • The classes are mutable
  • January is 0, December is 11
  • Date is not a date
  • Date uses years from 1900
  • Calendar cannot be formatted
  • DateFormat not thread-safe
  • SQL Date/Time/Timestamp extend Date

For a number of years the joda-time library (http://joda-time.sourceforge.net) have mitigated some of our problem, but this JSR should finally rid us of these problems. Since the spec lead for this JSR is the founder of Joda time, we must hope for the best.

We are all recommended to help in this JSR, so that we don’t end up with a third flawed API, so check it out at http://jsr-310.dev.java.net. It’s going to be really good…

Posted by Erik-Berndt Scheper at 8:06 on Saturday 10 May    Add 'Network applications with Apache MINA' site to delicious  Add 'Network applications with Apache MINA' site to technorati  Add 'Network applications with Apache MINA' site to digg  Add 'Network applications with Apache MINA' site to dzone

Trustin Lee of Red Hat held a presentation about Apache MINA, which has been forked as a separate top-level project from the Apache directory server. Apache MINA is a Java-based open-source network application framework that supports event-driven, (a)synchronous and unit-testable network implementations for sockets and datagrams, serial ports and in-VM pipes. Definitely something you should check out if at all applicable for one of your projects.

Posted by Erik-Berndt Scheper at 7:54 on Saturday 10 May    Add 'Performance considerations in concurrent garbage collected systems' site to delicious  Add 'Performance considerations in concurrent garbage collected systems' site to technorati  Add 'Performance considerations in concurrent garbage collected systems' site to digg  Add 'Performance considerations in concurrent garbage collected systems' site to dzone

Gil Tene and Michael Wolf from Azul Systems held an interesting presentation on concurrent Garbage Collection in Java. Concurrent and/or parallel GC is important, because a pause (or ‘full stop the world’) in the GC-process means that your application cannot conform to the SLA, which constitutes a failure in your application.

So what is a concurrent collector? A Concurrent Collector performs garbage collection work concurrently with the application’s own execution; whereas a Parallel Collector uses multiple CPUs to perform garbage collection. Many GC’s are both concurrent and parallel, but often do ‘stop the world’ if they don’t find a viable alternative. This often occurs in compaction (but not always and alone).

Read the rest of this entry »

Posted by Erik-Berndt Scheper at 7:34 on Saturday 10 May    Add 'General session with James Gosling' site to delicious  Add 'General session with James Gosling' site to technorati  Add 'General session with James Gosling' site to digg  Add 'General session with James Gosling' site to dzone

This morning was the last general session of this JavaOne, the ‘toy-show’ by James Gosling. Before the demos, he thanked Sun Microsystems’ Chief Researcher John Gage, who is retiring but first received his golden ‘Duke’ from Sun CEO Johnathan Schwartz (see photo).
GoldenDukeJohnGage

One of the interesting new (opensource) products is the visual VM, which just reached RC1 (See http://visualvm.dev.java.net). It requires JDK6 to run, but can observe the performance of JDK 1.4+ and display graphical information about heap usage, loaded classes, etc). Very promising, and (hopefully) useful for us as developers.

This JavaOne I have been convinced that NetBeans is clearly on its way to become a very good IDE. This session demonstrated the Javascript editor with code completion, quick fixes and runtime javascript debugging with a Firefox Plugin.

Also very cool (actually, much more so, was Java on the NVIdia APX 2500. Now there is a cellphone with a 3D graphics accelerator running OpenGL on Java.

Another area where Java is starting to shine is MMORG: game development using java with project darkstar. We were shown the JMonkeyEngine, which is a fault tolerant high performance gaming engine. For more information see www.projectdarkstar.com, www.jmonkeyengine.com and www.callofthekings.com.

Posted by Erik-Berndt Scheper at 6:59 on Saturday 10 May    Add 'Groovy and Grails: Changing the Landscape of JEE Patterns' site to delicious  Add 'Groovy and Grails: Changing the Landscape of JEE Patterns' site to technorati  Add 'Groovy and Grails: Changing the Landscape of JEE Patterns' site to digg  Add 'Groovy and Grails: Changing the Landscape of JEE Patterns' site to dzone

In this session Graeme Rocher en Guillaume LaForge of G2One described how JEE patterns must be adapted to suit Groovy and Grails; and that in some cases they are applied by the platform itself.

Groovy, Ruby, Lisp and Smalltalk support a Meta Object Protocol (MOP), which makes the semantics of a program extensible. In Groovy, every class has a MetaClass, which can be obtained with “def metaClass = obj.metaClass”. This makes it easy to obtain the methods from a class, e.g.

def obj = "Hello World!"
def metaClass = obj.metaClass
obj.metaClass.methods.each {
println it.name
}

So: the MetaClass defines the behaviour of the object, and the methods of the class be inspected using: “obj.metaClass.methods”. Similarly you can inspect if an object has method or property: obj.respondsTo() and obj.hasProperty().
Read the rest of this entry »


© 2018 Java Competence Network. All Rights Reserved.