Imagine a bacon-wrapped Ferrari. Still not better than our free technical reports.
See all our reports

vJUG Write Up: Live Reflection Madness

This week Heinz Kabutz joined the Virtual JUG for the first time with a session on Java reflection. Heinz is a Java Champion and recognised speaker as well as conference organiser, Java Specialists Newsletter creator and performance specialist. To join the vJUG and see these sessions live you should sign up and never look back!

Here’s the vJUG session if you wanted to watch it back in full:

It’s Puzzle Time!

Heinz started off with a simple puzzle that takes in a String of the form “1 + 2” which he splits and sums using a stream. Incidentally, Heinz at this point said “Streaming is going to lead to screaming”, as streams are much harder to debug! Nice line Heinz, I may use it myself! :) So we ended up with the following code:

    SillyPuzzlePrepare.prepareForSillyPuzzle();
    BufferedReader in = new BufferedReader(
        new InputStreamReader(
            System.in
        )
    );

    String line;
    while ((line = in.readLine()) != null) {
      int sum = Arrays.stream(line.split(" *\\+ *"))
          .mapToInt(Integer::parseInt)
          .sum();
      System.out.println(line + " = " + sum);
    }

This looks absolutely fine, and by the look of it the code would work nicely, although there is a weird call to SillyPuzzlePrepare.prepareForSillyPuzzle() right at the top, but we’ll ignore that for now. When we run, we get the following…

6 + 4
6 + 4 = 210
9 + 2
9 + 2 = 711
8 + 5
8 + 5 = 313

Interesting results, right? We look at SillyPuzzlePrepare in more detail and notice the following code:

  public static void prepareForSillyPuzzle() {
    try {
      Field value = Integer.class.getDeclaredField("value");
      value.setAccessible(true);
      value.set(10, 210);
      value.set(11, 711);
      value.set(13, 313);
      // snip -- more set calls...
    } catch (Exception silentlyIgnore) {
    }
  }

Heinz has taken the value field on Integer (an integer cache) and is setting it for Integers 10, 11, 13 and so on. So when these integers are used, the values 210, 711 and 313 are actually shown! The value field is private, but Heinz calls setAccessible on the field which allows him to set it. This is scary powerful, isn’t it?

Oh noes, Null Pointers!

Next, Heinz went on to talk about NullPointerExceptions and interestingly covered a topic which many have strong opinions on. First, consider the following constructor:

  /**
   * if name == null, we must throw a NPE
   * @param name
   */
  public Programmer(String name) {
    this.name = Objects.requireNonNull(name);
  }

It’s important the name parameter does not equal null, so Heinz uses a utility on the Objects class which does the following:

    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

This is a fairly standard code. If you haven’t heard of requireNonNull before, don’t worry, it was only added in Java 1.7. Heinz asked whether there’s a faster way in the Programmer constructor to perform the null check on the name parameter. Before you go on, take a look at the code and have a think. Hmmm you’re still reading, I thought we agreed you were going to have a think first! ;)

An option Heinz took us through was to invoke the getClass method on the name parameter. Heinz performs a timing test using between the name.getClass() version as well as Objects.requireNonNull(name) to see which is faster. He ran it in a for loop 10,000,000 times invoking each and it turns out that the Objects.requireNonNull(name) approach takes around 8795 ms, whereas name.getClass() run the same number of times only takes 436 ms. Nice, huh. So should we always use this approach?

TheShade says No!

TheShade, aka Aleksey Shipilev, who was also on the session in the audience, says the getClass call, which has been around since Java 1.3 is not a supported way to perform the null checks and also as Heinz showed, the compiler makes stackless NPEs for getClass(), which super improves speed, but really impairs readability of your debug should something go wrong. Both Heinz and Aleksey concur this is a weird thing to do, but still interesting food for thought!

There’s plenty more Heinz took us through in a really hands on and interesting session, so check out the full recording in full and become slightly closer to a reflection ninja!

Exclusive RebelLabs Interview

After the session Oleg, your friendly head of RebelLabs, spoke with Heinz, and you may be surprised to hear this thoughts on the Java language and others on the JVM! For this and more, check out the exclusive interview below:

You should really sign up to RebelLabs if you got this far. You clearly liked the content so you might as well be notified when more great content is available. Quick, it’s super easy, just add your email address. We’ll even show you a cool picture on the next screen!

 

  • David Leppik

    Well that explains all those stackless NPEs I’ve been getting for years. Too bad I still can’t track them down– since I still don’t have a stack trace. Grrr…

  • Heinz Kabutz

    You can turn off this “feature” with -XX:-OmitStackTraceInFastThrow, that way you will always get a stack trace :-)