Daniel Pitts’ Tech Blog

Archive for the ‘Esoteric Java Features.’ Category

Exceptional Exceptions!

Monday, July 21st, 2008

First, some boring philosophy about exceptions, then some interesting ways to circumvent the checked exception mechanism.

When designing your system, you should decide carefully which type of exception you want to throw. You have basically three choices: Errors, Exceptions, or RuntimeExceptions.

For unchecked exceptions, generally Errors shouldn’t be thrown directly, and RuntimeExceptions should be thrown (only) if the programmer could have prevented the exception before hand. This last point is arguable, but as a rule of thumb, works pretty well.

Checked exceptions should be used when a condition might occure, outside the programmers control, that isn’t what a typical work-flow would expect.  Check exceptions, if they can’t be dealt with, should bubble up to a user in an appropriate way.  The user should then be given an opportunity to decide what to do, such as retry the operation, report a bug, or go eat lunch and forget about it :-)

Now comes the interesting part. Circumventing checked exceptions.

There are at least two ways to throw a checked exception that isn’t actually checked.  Like with most of my esoteric Java features, they shouldn’t be used in production code. Both are hacks and both are ugly.

The first approach:  Class.newInstance().  Class.newInstance() will propagate any exceptions from the constructor to the calling code.  If your constructor throws a check exception, it will leak from Class.newInstance();

import java.io.IOException;
public class NoChecked1 {
   NoChecked1() throws IOException { throw new IOException("Leaked!"); }
   public static void main(String...args) {
      try {
          NoChecked1.class.newInstance();
      } catch (InstantiationException e) {
      } catch (IllegalAccessException e) {
      }
   }
}

The second approach: Thread.stop(Throwable t). stop(Throwable t) was deprecated a while ago, but Thank God Java Is Backward Compatible. calling this overload of stop will cause the thread to spontaneously throw an exception, checked or otherwise.

import java.io.IOException;
public class NoChecked1 {
   public static void main(String...args) {
      Thread.currentThread().stop(new IOException("Leaked again"));
   }
}

Yikes. Don’t try this at home kids.

Almost Useful: Java Type Intersection.

Friday, November 23rd, 2007

First, for my subscribers that celebrate it, Happy Thanksgiving!

I’ve written about it before, but I think its worth revisiting. Type intersection would be a highly useful feature if not for one thing. “It is not possible to write an intersection type directly as part of a program; no syntax supports this.” – JLS (§4.9). That seems like a poor excuse to not support a feature as potentially powerful as type intersection could have been.

They were bold enough to add syntax all over the place for Generics. They added new syntatical meanings for ‘?’ ‘<’, and ‘>’. As a matter of fact, they added a syntax within that construct for handling Type Intersections. Would it really be that difficult to reuse that syntax outside of capture conversions and type inference? Heck, maybe even make it reifiable, although that’s not *as* important.

One example others have used in the past where it would be useful to have this type intersection is with the marker interface RandomAccess. While marker interfaces are less useful now that we have annotations, it none-the-less exists, and can be useful for ensuring that the user of an algorithm passes in a compatible list.

For example, its quite possible to do the following, even with the currently crippled implementation of type intersection.
<T extends List<String> & RandomAccess> void foo(T list) { ... }
You know that you’re getting a random access list. The pain point is that you can not do the following:
<T extends List<String> & RandomAccess> T foo() { return new ArrayList<String>(); }
The reason that isn’t legal is quite simple, even if its not obvious. T is any type that satisfies List<String>&RandomAccess, so you don’t know that it is an ArrayList. You might have MyNonArrayList<String> list = foo(); Oops, that would be an incompatible assignment.

The better approach would be to have the return type be an explicit type that is List<String>&RandomAccess. As a matter of fact, my suggestion is to use that syntax exactly, unless there is a compiler-grammar reason not to. So, our T foo() line becomes:
List<String>&RandomAccess foo() { return new ArrayList<String>(); }
So then we can do: List<String>&RandomAccess list = foo(); Actually, we could just use List<String> list=foo() if we don’t care about RandomAccess.

An important addition to make to this would be casting. For legacy support, if I have a List<String>, but I know that it should be an ArrayList (or some other RandomAccess), I should be able to cast: foo((List<String>&RandomAccess)list);

Shrinking Source Code: Java initialization

Saturday, October 20th, 2007

There have been a few discussions on how to do a particular task with the smallest amount of “code”. Some people talk about this with regards to soure code, and others with regards to object (a.k.a machine-instructions or byte code). While the later has some actual application, its often more “fun” to talk about the former.

Shrinking source code down for no other reason is generally bad practice, but it is an interesting exercise. I think that in this article we can distill the basic concept down to what is the smallest valid (in characters) Java source file that will compile, and when run does absolutely nothing.

For our first attempt, lets try the straight-forward approach. Not bending any rules.

class C{public static void main(String[]a){}}

That is 45 characters long. This compiles (javac C.java) and executes (java C) .Nothing spectacular, and there doesn’t appear to be anything superfluous there, but I assure you there is.

Think back to the JLS. Specifically, before the JVM can execute main() on a class, it must initialize it first (JLS 12.4.1).This gives use another way to execute code.

class C{static {} public static void main(String[]a){}}

This is a little longer, but bear with me. It still compiles and executes, just like our previous versions. What about removing main now?

class C{static{}}

This is indeed very short, and compiles just fine, but unfortunately we get Exception in thread “main” java.lang.NoSuchMethodError: main. Well, that doesn’t exactly do nothing, which is what our goal is. Note that we can put code into the static initializer.

class C{static{System.exit(0);}}

Now we’re down to 32 characters, and it compiles and does nothing. Sweet. What happens is that the JVM executes the static initializer before looking for the main method. The initializer tells the JVM to terminate (JLS 12.8), so it complies. Hence, no exception.

Is there anything else we can rid ourselves of? With the advent of Enums in Java 5, the answer is yes! We don’t need to explicitly create a static initializer, because enums will do that for us.

enum C{A;{System.exit(0);}}

27 charecters long, and it compiles and does nothing. Amazing. So what’s happening here? Enum types in Java are actually classes. Furthermore, they are singletons. In this case, the compiler creates two classes. C extends Enum, and A extends C. When we run java C, the JVM loads the class C which has a static initializer that sets C.A = new A(), which starts the instance initialization (JLS 12.5) process. Part of this process is to call the initializer of the parent class (in this case C). We added an instance initializer in C which kills the JVM.

So there you have it. The smallest possible Java program which does absolutely nothing (as far as I know). When trying to create the smallest possible Java program which does something, you would probably be wise to start from this template, unless you find a tricky way of having existing library code closing the JVM after doing your bidding otherwise. Not terribly useful, but somewhat entertaining, and it might help give you a better understanding of what goes on under the hood.

As with most of my esoteric Java features, don’t try this in production code.

Type Intersection in Java, or: Interest in Interfaces is Invaluable.

Tuesday, March 6th, 2007

There was an interesting philosphical question posted in the comp.lang.java.programmer newsgroup the other day. Patricia, the original poster, had a question about using ArrayList as the declared type. She wanted to convey the fact that she wanted a List which has constant time random access methods, as this is an important property for her algorithm. Many of us live by the rule “Always use an interface, never a concrete type,” and she was questioning this. I personally think this dogma is a little to broad. However, it usually makes sense when using Java collections. As a matter of fact, you’ll find a lot of my code uses Collection instead of Set or List.

I guess Sun also thought it was important to convey constant time random access; they created an interface called RandomAccess just for that. RandomAccess is a marker interface for a List implementation to “indicate that they support fast (generally constant time) random access.”

Thats all well and good, but there’s a problem here.

   RandomAccess myList = new ArrayList<Integer>(); // This compiles fine

   myList.get(0); // Whoops, compile error. RandomAccess doesn't extend List, so no get method;

Java 1.5 *almost* supports what we want… We want to say “Give me an object that is RandomAccess AND List<Integer>”. With the introduction of Generics, Java introduced Type Intersection. Unfortunately, they only introduced it in the context of Generics.

  // Processes a RandomAccess List of integers, compiles fine

  public <L extends RandomAccess&List<Integer> > void processList(L list) {
      // ...
  }

  // Fails to compile.
  public List<Integer> process(Collection<Integer> input) {
    RandomAccess&List<Integer> output = new ArrayList<Integer>(input);
    //  ...
    return output;
  }

While this is too convoluted to answer Patricia’s philosophical question. It does bring us to an interesting, if incomplete, feature of Java.

(more…)

Instantiating Java inner-class objects, from a different class.

Tuesday, January 9th, 2007

It occurred to me one day, that if you’re inner class isn’t static, it needs to have a copy of the “this” reference of the outer class. Most of the time, inner classes are only instantiated from within the containing outer class, so it was apparent where the “outer.this” reference came from.

I started thinking of how one might instantiate the inner-class object from a completely separate class. I spent a little time experimenting, why bother reading the JLS, and found the right syntax.
I first tried “new outerObject.InnerClass()”, but that was a syntax error. My second try was the right one. “outerObject.new InnerClass()”. While it looks a little awkward (and I would never do it in production code), it is useful to know how it works. I wrote up an example program to demonstrate how it happens.
(more…)