Tuesday, February 17, 2009

Crazy Java Puzzler

Here is a puzzle for you. As the title promises, yes, it's quite crazy. It is assumed that you already are a die-hard Java programmer that knows the language better than the skin of his very palm. Ok, maybe not that much, but anyway.

As a little history, I had posted this on the Hellenic (i.e. Greek) Java User Group, which used to have an online forum, now defunct (too bad). So if you happen to be on those few who happened to see the solution there, just restrain yourself, I don't want any stinkin' spoilers!

Enough of intro. Here is the code:

interface id {
  <id> Void read(List<id> list);
  <id> Void read(List<id> list);
  <id> Void read(List<id>... list); //*
}

The puzzle: What is the shortest edit (measured in inserted/deleted characters) that makes this program compilable? (While keeping the read methods overloaded).

(We're not talking any kind of cheat like compiling with some arbitrary compiler, just the plain Java compiler. Oh, and commenting out lines of code is the wrong answer too).

The problem, obviously, is that the two methods produce a name clash.Well, it's all yours! Hit it hard! Can you nail it?

* [10-Mar-10] As Sureth below points, a solution would be appending "[]" to a list, a 2-character ending. Indeed. Sloppy of me. That basically ruins the fun, so I have to this third overloading to avoid [] and varargs solutions. Now (hopefully) only the intended solution is there, hopefully in not too artificial a puzzle. Oh, by the way, trying this problem is not a waste of time: it reveals a deeper knowledge about the java platform and gives a new (for those unaware of it) technique that can be used in API design. It's already the "magic sauce" of the nice API of a popular testing-related framework.

Saturday, January 24, 2009

A DSL to output XML, in Java

Yesterday, I had to output some simple XML in Java. I couldn't find any decent way of doing this out there. Writing with SAX sucks, and DOM didn't look much better either. I just println'ed the thing out and went on my way.

Today I revisited the problem. I wanted to easily express the XML tree structure and evaluate it as something, a String for instance. I came up with a neat solution heavily based on generics.

Here is a usage example of it:



XmlBuilder xmlBuilder = new XmlBuilder();
String s = Xml.newDocument(new XmlBuilder())
.kid("start")
.kid("kid")
.kid("subkid").attr("key", "value")
.close()
.close()
.close();

System.out.println(s);

Note that calling close() sometimes returns a node (that can also close()), but the last time returns directly a String!

This is the output:



<?xml version="1.0"?>
<root>
<child>
<sub_child key="value">
</sub_child>
</child>
</root>


Here is the simplified crux of the idea:



public class Node<T> {
private final String name;
private final T returnValue;
private final XmlHandler handler;

Node(String name, T returnValue, XmlHandler handler) {
this.name = name;
this.returnValue = returnValue;
this.handler = handler;
}
//...

Node<Node<T>> child(String label) {
return new Node<Node<T>>(label, this, handler);
}

T close() {
//...
handler.endNode(name);
return returnValue;
}
}
The magic part is methods child() and close(). Node<T> means "when close() is called, return T". Imagine we want to output an XML as a string. We want the root node to be of type Node<String>, so when that closes, we get a String back. Right. Now pay attention to method to the child() method. It returns a Node<Node<T>>, meaning "here is a node that when it closes, you return back to this node" (and we give "this" as a returnValue of the new node).

This means that the compiler can figure out the nesting level of each Node. The root Node is just Node<String>. All children of that are of type Node<Node<String>>. Children of those children are Node<Node<Node<String>>>, and so on. When a close() is invoked, a nesting goes away, like pealing an onion kind of way, till we get back to the result we want.

XmlBuilder is similar to ContentHandler, but simplified. Here it is:


public interface XmlHandler<T> {
void startNode(String name, Map attributes);
void endNode(String name);

T result();
}


The above library can be used with any implementation of XmlHandler - producing a String is only a viable use-case. One could easily create a DOM as well, simply by creating another XmlHandler implementation. XmlBuilder in the example above is XmlHandler, and this is why the root node is of type Node. We could implement an XmlHandler and get back the root node as Node.

To conclude, this is a nice DSL for expressing XML trees, combined with an abstract handler to process the tree. A point to highlight is that this modelling allows the compiler to know the nesting of each node, so it knows how many consequtive "close()" I can call for example. I must call the right amound of close() to get back to the result I want, or else a type error will occur.

Still, this kind of type-safety doesn't automatically translate to valid XML, because the user could store a node somewhere and close it twice - we would only find that at runtime.

All in all, that was a good exercise in Java generics. I would give the complete source if there was an easy way to attach it here, but I guess the margin is too narrow. :-)



Tuesday, January 20, 2009

The Subtleties of PhantomReference and finalization

A common misconception regarding PhantomReference is that it is designed to "fix" the dead object resurrection problem that finalizers have. For example, this old java.net blog says about phantom references:

PhantomReferences avoid a fundamental problem with finalization: finalize() methods can "resurrect" objects by creating new strong references to them. So what, you say? Well, the problem is that an object which overrides finalize() must now be determined to be garbage in at least two separate garbage collection cycles in order to be collected.

Well, yeah. Except for the fact that even PhantomReference can let their referred objects be resurrected. This is even how it can be done:

Reference ref = referenceQueue.remove();
//ref is our PhantomReference instance
Field f = Reference.class.getDeclaredField("referent");
f.setAccessible(true);
System.out.println("I see dead objects! --> " + f.get(ref));
//This is obviously a very bad practice
Yes, unreachable objects are really referenced from the Reference#referent field, seemingly strongly, but no, the garbage collector makes an exception for that particular field. This fact also contradicts what the previous blog declares:
PhantomReferences are enqueued only when the object is physically removed from memory.
Which is not true, as we just saw. Javadocs also say:
Phantom references are most often used for scheduling pre-mortem cleanup
So if PhantomReference was not meant to fix the resurrection problem (which indeed is serious, as pointedly proven by Lazarus, Jesus and many others), what is it useful for?

The main advantage of using a PhantomReference over finalize() is that finalize() is called by a garbage-collector thread, meaning it introduces concurrency even in a single-threaded program, with all the potential issues (like correctly synchronizing shared state). With a PhantomReference, you choose the thread that dequeues references from your queue (in a single-threaded program, that thread could periodically do this job).

What about using WeakReference? It seems to also fit the bill for pre-mortem clean-up. The difference lies in when exactly the reference is enqueued. A PhantomReference is enqueued after finalization of the object. A WeakReference is enqueued before. This doesn't matter for objects with no non-trivial finalize() method.

And how exactly are you supposed to clean-up a dead object you don't even know? (PhantomReference's get() method always returns null). Well, you should store as much state as needed to perform the clean-up. If cleaning up an object means nulling an element of a global array, then you have to keep track of the element index, for example. This can be easily done by extending the PhantomReference and adding the fields you want, and then create PhantomReference instances from that subclass.

Now lets talk about even darker corners than these.

Lets say that it is even darker relating finalization than this. If you are about to write a clean-up hook for an object (by finalize() or with a [Weak|Phantom]Reference), and you happen to call a method on it while there is it is strongly-referenced only from the thread stack (i.e. a local variable), and you happen to invoke a method to that object, bad things can happen.

This is very unfortunate. For performance reasons, the VM is permitted if it can to reuse the register that holds the object reference, thus making the object unreachable. So, during the method invocation on an object, finalization might be executed concurrently, leading to unpredictable results (finalize() could modify state that is needed by the other method execution). This should be extremely rare though. Currently, this can be fixed by:



Object method() {
//do work here
synchronized (this) { }
return result;
}


public void finalize() {
synchronized (this) { }
//do work here
}
This will only affect you if you have an object referenced only from the thread stack and either one holds:
  • it has a non-trivial finalize() method
  • there is a [Weak|Soft|PhantomReference] to it, enlisted to a ReferenceQueue, and there is a different thread that dequeues references from ReferenceQueue
To conclude, the safest clean-up for objects is to have a ReferenceQueue and a PhantomReference, and you use the same thread that uses the object to do the clean-up. (If this the clean-up is performed from another thread, synchronization will probably be needed, and the above issue might be relevant).

You may check these JavaOne slides too.



Sunday, January 18, 2009

Beware of hidden contention of Math.random()

Did you know that Math.random() uses a single java.util.Random instance, which itself is thread-safe*? What this means is that if you have a benchmark with multiple threads that are supposed to run in parallel, and all of them constantly generate random numbers through Math.random(), they will all compete for its lock and can deteriorate into running serially.

So, beware of this pitfall. It is preferrable to share instead a ThreadLocal, as for example in:

static final ThreadLocal localRandom = new ThreadLocal() {
    @Override protected Random initialValue() {
        return new Random();
    }
};

...
Random random = localRandom.get();

This is already quite a common practice when using SimpleDateFormat in web applications, where it is more efficient to have a separate instance per thread rather than have all threads contend for a single instance (which tends to be quite computationally intensive).

A better alternative is slated for inclusion in Java 7: ThreadLocalRandom. This is like a thread local Random, only it is not thread-safe, so some unnecessary overhead is avoided. There is a slight inconvenience that you can't control the initial seed - I could be wrong though (the javadoc says that setSeed throws UnsupportedOperationException, but the implementation seems to be that exactly one call of this method is allowed).


* Using volatile reads and compare-and-swaps, which makes it lock-free



Monday, January 12, 2009

Comments on "Is Java Obsolete?"

Today I read this blog: Is Java obsolete? (spoiler alert: Scala inside)

Apart from the title which used to be an attention-grabbing (along with "java is dead") but not really any more, I am in a quite similar situation as that author.

To begin with, I'm a Java programmer. I've invested (literally) thousand hours of my own time in it the past few years, eagerly learning its ins and outs, and also use it for a day job. I can't attain the same level of productiveness using anything else, without spending (much) much time learning it.

Now, on with the post. It's about someone starting http://www.scala-lang.org/. And doing it, feels (like me) that poor Java-the-language misses so much power (no closures, no FP...). (By the way here is how I picked up Scala: by reading a paper/overview on it, watching a talk by Martin Odersky, and I'm currently reading Programming in Scala).

I played a bit with various scripting languages. I quite like Ruby/Python, but when I found out what performance implications those pertain, I grew very skeptical (see for example this performance essay of Guido and amaze). What I saw was performance characteristics (i.e. "slow"), not in the fixable sense Java was in its start, but not fixable, due to language design itself. So I decided I needed something else (and thankfully, Scala was there all along). 

Previously, I also explored some other Java-friendly alternatives, like Groovy. In the words of an anonymous commentator of the above blog: "you might want to have a look at the Groovy language, instead of Scala". Now that's a motivation, heh. Anyway. My experience with groovy was not so good. I looked at it more than a year ago, and the compiler pretty much sucked - I couldn't understand any of the syntax errors. I had the intention of learning it, to at least be able to use it in small-scale scripting tasks, on the console. But that proved futile: it was so easy getting wrong, that I really had to grok most of the groovy language to be able to use it, and that just wouldn't pay off for small-scale scripting tasks. For large-scale, just forget about it. This quote from groovy's main page nicely summarizes the reason: 
  • You will not get compile errors like you would in Java for using undefined members or passing arguments of the wrong type. See Runtime vs Compile time, Static vs Dynamic.
So, I found the comment's last part "... instead of Scala" quite hilarious. Maybe "complementary", but "instead"? Anyway, I don't want to go there just yet.

I remember actually settling for BeanShell, since it was much easier to use. Less powerful, true, but not so cumbersome - easy to put to actual work.

But those are things of the past. I'm quite happy to be able to have both 1) a very powerful oo-functional language, and 2) a very powerful type systems. Types, after all, is the natural currency of Java (as nicely said by crazy bob lee). I tend to view types as language extentions, i.e. "things you can do if you reach here". It's like having the author of a library there with you, giving you advice and direction all the time, whereas in dynamic languages all you have is a string soup where you have to attain the skill of choosing the right string to do the job (and while being at it, write a test proving you picked the right string).

To sum up, I can't picture groovy, or any dynamically typed languages replacing java anytime soon. I also don't see scala replacing java anytime soon, either. But I like the ability to enjoy more powerful programming in scala, while the rest of the world can keep using plain java, and all be peaceful and well. 

Enough rambling from me, on with actual work :)