﻿<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="atom-style.css"?>
<!--
    Je suppose que ce commentaire empêche que Firefox considère ce document XML comme flux RSS parce que la balise ouvrante est plus loin que les 512
    premiers octets. C'est à mon avis trop simple (ça s'appelle du "content sniffing" mais si ça peut faire fonctionner mon site, je ne vais pas m'en
    priver. Allez, il en manque encore un tout petit peu, et on a les 512 octets qu'il faut pour que le flux RSS ne soit pas découvert.
    -->
<a:feed xmlns:a="http://www.w3.org/2005/Atom" xmlns="http://www.w3.org/1999/xhtml">
  <a:author>
    <a:name>Matthias Ernst</a:name>
    <a:email>blog@mernst.org</a:email>
  </a:author>
  <a:title>Matthias Ernst's Weblog</a:title>
  <a:id>http://mernst.org/blog/rss.xml</a:id>
  <a:link href="http://www.mernst.org/blog/rss.xml" rel="self"/>
  <a:link href="http://www.mernst.org/jess/resume.html" rel="wife"/>
  <a:subtitle>Mostly geeky stuff</a:subtitle>
  <a:updated>2007-10-05T19:18:00+02:00</a:updated>
  <a:entry>
    <a:title>Sidebar</a:title>
    <a:content type="xhtml">
      <div style="position: relative">
        <div style="width: 50%">
          <h3 style="display: inline">About</h3>
          I'm a passionate, paid tinkerer in all things Java.
          <h3 style="display: inline">Links</h3>
          <a href="#Get-the-Jist">jist</a>
          -
          <a href="https://sprong.dev.java.net/">sprong</a>
          -
          <a href="https://axt.dev.java.net/">axt</a>
          -
          <a href="http://ulc-community.canoo.com/snipsnap/space/Spring+Integration">ULC with Spring</a>
          -
          <a href="http://virtualmachine.de/">heapprofile</a>
          -
          <a href="http://www.mernst.org/ariadna/index.html">ariadna</a>
          <h3 style="display: inline">Syndicate</h3>
          <a href="rss.xml">Atom 1.0</a>
        </div>
        <br style="clear: both"/>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#sidebar</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#sidebar"/>
    <a:updated>2007-06-11T13:00:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Re: Budget Reservation Confirmation</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="re-budget-reservation-confirmation" href="#re-budget-reservation-confirmation"></a>
        <p>
          So it seems I'm exhibiting a huge amount of naivety about how car rental works at Budget Inc.
          Four strong indications:
        </p>
        <ol>
        <li>Assumption: the online reservation system "knows" about the number of
        cars available at a rental location. It will not let you make a reservation
          when no cars are available and it will not send you a "confirmation" mail
          saying "your rental car has been reserved".</li>
        <li>Assumption: Representatives at the rental location are aware of your reservation
        and are expecting you at the time indicated therein.</li>
        <li>Assumption: A representative that - after debunking assumptions 1 &amp; 2 - offers
          to transfer your reservation to
        another location nearby has a better overview of availability in her software and
        will make sure a car will be waiting for you there.</li>
        <li>Assumption: The map handed to you by the representative actually carries the correct
        address of that other location.</li>
        </ol>
        <p>
          Needless to say, all four assumptions have been proven wrong at Budget Embarcadero, San Francisco, and FWIW said
          representative had already closed shop by the time #3 came to pass. It wasted like
          2 hours of a precious Saturday that I had planned to spend on the road - boy am I pissed.
          And I just refuse to accept the idea of having to question every statement made by a representative
          and jotting down the name of every person I talk to. Get your shit together, Budget, before I rent
          with you again.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#re-budget-reservation-confirmation</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#re-budget-reservation-confirmation"/>
    <a:updated>2008-02-16T15:17:00-08:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>To Rephrase Reginald</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="to-rephrase-reginald" href="#to-rephrase-reginald"></a>
        <p>
          Reginald
          <a href="http://feeds.raganwald.com/~r/raganwald/~3/233276343/blodgetts-law.html">quotes</a>
          Blodgett's Law and points to verbos languages:
        </p>
        <blockquote>
          A development process that involves any amount of tedium will eventually be done poorly or not at all.
        </blockquote>
        <p>
          If I read him correctly, Reginald is trying to say: "Programming Languages that require a
          handwritten test suite to prove basic type correctness will eventually be abandoned."
          <i>Happily trolling away ...</i>
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#to-rephrase-reginald</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#to-rephrase-reginald"/>
    <a:updated>2008-02-14T20:47:00-08:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Děkuji Vám</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="a-big-thank-u" href="#a-big-thank-u"></a>
        <p>
          Yet another installment in that long list of pleasant surprises (example made up).
          Imagine I've written a method that takes a map and prints its entry set. Now I
          want to generalize this method to print any set and to make the caller pass in the
          entry set himself. Highlight <code>map.entrySet()</code> and press Apple-Alt-P:
        </p>
        <img src="removeparam.png" alt="Introduce Parameter refactoring"/>
        <p>
          Notice the last option "Remove parameter no longer used"? It makes
          my refactoring just one consistent operation, one I'm doing quite regularly and
          this is really just awesome. Steve Yegge
          <a href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html">dismisses</a>
          it as "industry excitement about
          manipulating code as algebraic structures". He's happier pushing around compressed ASCII.
          Matter of taste.
        </p>
        <p>
          Anyway, making my employer buy IDEA licenses is already a form of positive
          feedback, but I think it's about time to extend a BIG thank you to the
          guys at JetBrains. You have fundamentally and continually improved my work
          experience over the last >5 years --- I can't even remember anymore when I retired
          emacs. Cranking out and massaging code is what I do and every friction removed helps
          keep me sane.
        </p>
        <p>
          &lt;/vendor-promotion>
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#a-big-thanks</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#a-big-thanks"/>
    <a:updated>2008-01-12T10:44:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Actually type inference has been here for a long time</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="ide-type-inference" href="#ide-type-inference"></a>
        <p>
          There are so many complaints that variable declarations in Java are written
          like so: <em>type var = new type();</em>.
        </p>
        <p>
          Not in my IDE. In my IDE, it's: <em>new type() CTRL-ALT-V/F/C var RETURN</em>. Or
          <em>type var = new SHIFT-CTRL-SPACE RETURN</em>. And should I want to change the type,
          I typically rinse and repeat.
        </p>
        <p>
          This is not to say that it doesn't inhibit readability and that a compiler shouldn't do the job.
          But people who actually type the type twice today simply don't use the right tool.
        </p>
        <p>
          [2008-01-06] Kevin writes: <em>You must be joking. That's not type inference.</em> Of course I'm joking and not.
          Type inference refers to the process performed by the programming environment
          that fills in -redundant- type declarations that have been omitted from the source code, typically in two
          cases: variable declarations (type is that of the initialization expression) and function calls (type
          parameters derived of value parameters' types). This process is hopefully defined by the language specification.
        </p>
        <p>
          However, we have to keep in mind that this definition is very focused on the textual input that is source
          code. The underlying assumption is that the programmer types and reads the source code as a sequence of
          characters --- so we need the source code to be as concise as possible. I'm saying that we need to factor
          programming environments in more. I'm saying I don't need type inference for locals as badly as other people
          seem to because my interface to Java is much more than the JLS and a text editor, my IDE helps me.
        </p>
        <p>
          There are more examples like this. No one argues against long variable names because they are so hard to type.
          Opponents of extension methods as recently proposed say that a reader of a call site can no longer figure out
          easily where the method is defined. Not in my world: CTRL-Hover over the symbol and I see the definition site.
          Smalltalkers don't ever bitch about the class definition syntax since they almost never see it. And why has
          no one ever proposed getting rid of the package declaration statement in Java although it is predetermined by
          the directory location? Exactly, no one writes these by hand anyway.
        </p>
        <p>
          In the end it's a language vs tool argument: what I say makes the IDE great, linguists say they wouldn't need
          if the language were better. Don't get me wrong, I'm all for local variable type inference. And I loathe
          code generation. I'm just getting pretty tired of endless my language vs your language when the comparison is
          based on the textual representations and not on the net programming effort.
        </p>
        <p>
          [2008-01-07] Rémi and Ben raise an important point below: some types cannot be
          written down in Java, especially of anonymous inner classes.
        </p>
        <h3>Comments</h3>
        <div class="comment">
          <p>
            Kevin: You must be joking. That's not type inference.
          </p>
        </div>
        <div class="comment">
          <p>
            <a href="http://weblogs.java.net/blog/forax/">Rémi Forax</a>: Matthias, yes IDE helps but
            it will bother me to have to use the mouse over every variables to understand
            a code.
            Reading codes is a part of my job
            (finding bugs in student codes)
            and i love Java because i am able to
            do that pretty fast.</p><p>
          Moreover, Java type system own types that
          are not writeable like the type of null,
          the intersection of interfaces, wildcard capture.
          By example, try to find with your IDE,  the type of foo in the code below:</p>
          <pre><![CDATA[List<?> list = null;
foo := null;   // inference here
list.add(foo);
]]></pre>
          Rémi
        </div>
        <div class="comment">
          <p>
            Ben: Rémi makes a good point.  What if you have an anonymous inner class with a method that you want to be
            able to call or a field you want to reference?
          </p>
          <pre><![CDATA[
Object o = new Object() {
 void doSomething() { }
 int aField;
};

// Won't compile
// o.doSomething();
// o.aField;

with type inference:

final o = new Object o = new Object() { void doSomething() { } };
o.doSomething();
o.aField;  ]]></pre>
          <p>
            AFAIK, this is the main reason local variable inference was added to C#3 - to allow anonymous types for LINQ expressions.
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#ide-type-inference</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#ide-type-inference"/>
    <a:updated>2008-01-05T22:00:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Swimming with the stream</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="swimming-with-the-stream" href="#swimming-with-the-stream"></a>
        <p>
          JAXB is great. Not a doubt. Just as an academic exercise, in order to
          write a big document, can we avoid
          building the object graph in advance? Could we still profit from strongly
          typed binding? The best answer I found was this:
        </p>
        <p>
          Write an interface that corresponds to your complex type. Where JAXB expects
          a property to read from, have a method that accepts a closure that accepts
          an instance of the child element type. For elements of simple type, provide
          a simple setter:
        </p>
        <pre>
          public interface Artist {
          public Artist name(String name);
          }

          public interface Album {
          public Album artist({Artist=>Void} artist);
          public Album title(String title);
          }
        </pre>
        <p>
          In order to produce an Xml document with this, we need to bootstrap ourselves
          an Album instance and write through typed calls:
        </p>
        <pre>
          write("album", Album.class, {Album a =>
          a.title("mein leben")
          .artist({Artist a =>
          a.name("Charlotte Saenger")
          })
          });
        </pre>
        <p>
          Not pretty. The best I could think of. Seems like this
          won't have a great future... Just for the sake of completeness, an
          implementation _sketch_:
        </p>
        <pre>
          public class StreamBinder {
          Model m;
          ContentHandler out;


          &lt;T> void write(String uri, String element, Class&lt;T> c, {T=>void} t) {
          out.startElement(uri, element, "", new AttributesImpl());
          t.invoke(bind(c));
          out.end(uri, element, "");
          }

          &lt;T> T bind(final Class&lt;T> c) {
          return c.cast(Proxy.newProxyInstance(c.getClassLoader(), new Class[] {c}, new InvocationHandler() {
          public Object invoke(Object o, Method method, Object[] args) throws Throwable {
          String uri, element = model.lookup(c, method);
          Class elementType = model.lookup(c, method);

          // ##handle simple content
          write(uri, element, elementType, args[0]);
          return o;
          }
          }));
          }


          public static void main(String[] args) {
          model = reflectOver(Album.class);

          new StreamBinder(out, model)
          .write("album", Album.class, {Album a =>
          a.title("mein leben")
          .artist({Artist a =>
          a.name("Saenger")
          })
          });
          }
          }
        </pre>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#swimming-with-the-stream</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#swimming-with-the-stream"/>
    <a:updated>2007-12-22T00:20:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>S3ad</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="S3ad" href="#S3ad"></a>
        <p>
          So I tried Transmit, Forklift and S3cmd and _none_ allows me to set
          the content-type. Only s3cmd can make items world-readable in an easy
          way. I can't believe I just had to hack s3cmd to make '--mime-type' work.
        </p>
        <p>
          Also sad: this file as application/atom+xml would be spec compliant, but Camino only
          renders application/xml. So I'm going to stay with xml I guess...
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#S3ad</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#S3ad"/>
    <a:updated>2007-12-21T22:34:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>PUT to work</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="PUT-to-work" href="#PUT-to-work"></a>
        <p>
          I want to second
          <a href="http://devhawk.net/2007/12/05/Durable+And+RESTful.aspx">Harry</a>
          and Patrick's comment over at
          <a href="http://www.dehora.net/journal/2007/12/21/durable-and-restful/">Bill's blog</a>. I think
          all of Bill's concerns can be addressed:
        </p>
        <p>
          Trust: If you have multiple clients, you need to do access control anyway (they might PUT to each other's
          items, even if created by POST).
        </p>
        <p>
          Accidental overwriting: handled by 'If-None-Match'.
        </p>
        <p>
          Conflicts: with PUT, you can route requests according to URI and do efficient conflict
          resolution/avoidance on the local server shard.
        </p>
        <p>
          Apart from idempotency: let's remember that Atom is for syndication - that typically entails already existing
          items
          with client-specific ids. That an Atom server forces its own id space onto me that I need to map to mine is a
          nuisance,
          not a feature. And for the really stupid clients: serve an Atom feed of fresh, unused ids.
        </p>
        <p>
          On the same level, I've never been into the "primary keys must be database-generated" mantra.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#PUT-to-work</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#PUT-to-work"/>
    <a:updated>2007-12-21T20:46:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>mernst.org moved and outsourced</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="mernst-org-moved-and-outsourced" href="#mernst-org-moved-and-outsourced"></a>
        <p>
          As a consequence of my move to Zurich, I had to change providers for mernst.org. I was torn
          between two extremes: a "real" server where I could experiment and put Java services on the web
          and a minimalistic approach where http file delivery and mail run with the big guys. I have chosen
          the latter route - a mere domain registration with a german provider, http traffic is CNAMEd to my
          bucket www.mernst.org at Amazon S3, email lives on Google Apps.
        </p>
        <p>
          What I'm still looking for is a free/pay per usage service that would accept [captcha'd] [XHR]
          POST requests for my domain, store them and offer them as a feed that I could process at
          my discretion, i.e. when I'm online.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#mernst-org-moved-and-outsourced</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#mernst-org-moved-and-outsourced"/>
    <a:updated>2007-11-24T23:24:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Non-blocking IO Iterators</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="non-blocking-io-iterators" href="#non-blocking-io-iterators"></a>
        <p>
          When you deal with non-blocking IO your IO tasks turn from methods into state machines. You do some
          IO on every transition, each state representing what kind of IO you would like to do next. In combination
          with something like the<a href="http://chaoticjava.com/posts/category/code/java/frameworks/yielder/">yielder
          iterator byte rewriting framework</a>, we can turn these back into iterator methods that
          <em>yield</em>
          interest sets, making NIO a little easier again:
        </p>
        <pre>
          // this is sample code that neither implements proper error handling
          // nor a tunable buffer allocation policy or anything ...
          // it just demonstrate how an NBIO task looks as an iterator of InterestSets
          public class Copy extends Yielder&lt;InterestSet> {
          public final ReadableByteChannel source;
          public final WritableByteChannel target;

          public Copy(ReadableByteChannel source, WritableByteChannel target) {
          this.source = source;
          this.target = target;
          }

          protected void yieldNextCore() {
          try {
          ByteBuffer b = ByteBuffer.allocate(4096);
          while (true) {
          switch (source.read(b)) {
          case -1: // EOF
          yieldBreak(); return; // yieldBreak() actually necessary?
          case 0:
          yieldReturn(new InterestSet().read(source));
          break;
          default:
          b.flip();
          while (b.remaining() > 0)
          if(target.write(b) == 0) yieldReturn(new InterestSet().write(target));
          }
          }
          } catch (IOException e) {
          // hmm what about that
          }
          }
          }

          ... where:

          public class InterestSet {
          public final HashMap&lt;Channel, Integer> interestSet = new HashMap&lt;Channel, Integer>();
          public Long delay;

          public InterestSet withInterest(Channel c, int op) {
          interestSet.put(c, or(interestSet.get(c), op));
          return this;
          }

          public InterestSet waitFor(long delay, TimeUnit u) {
          this.delay = TimeUnit.MILLISECONDS.convert(delay, u);
          return this;
          }

          public InterestSet read(Channel c) {
          return withInterest(c, SelectionKey.OP_READ);
          }

          public InterestSet write(Channel c) {
          return withInterest(c, SelectionKey.OP_WRITE);
          }

          public InterestSet connect(Channel c) {
          return withInterest(c, SelectionKey.OP_CONNECT);
          }

          public InterestSet accept(Channel c) {
          return withInterest(c, SelectionKey.OP_ACCEPT);
          }

          private int or(Integer a, int b) {
          return a == null ? b : a|b;
          }
          }
        </pre>
        <p>
          <em>Disclaimer:</em>
          I haven't actually run this code yet - just to get an idea how it would look like.
        </p>
        <h3>Comments</h3>
        <div class="comment"><a href="http://chaoticjava.com/">Aviad Ben Dov</a>: Actually, yieldBreak() isn't really
          neccessary. Reaching the end of the yieldNextCore method is an implicit yieldBreak. So, you could either
          yieldBreak, or to break from the while loop - if that's the intention.
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#non-blocking-io-iterators</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#non-blocking-io-iterators"/>
    <a:updated>2007-10-05T19:18:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Extract Method Reloaded</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="extract-method-reloaded" href="#extract-method-reloaded"></a>
        <p>
          Three steps of refactoring I often perform: given a complex expression
          <em>exprA(exprB)</em>
        </p>
        <ul>
          <li>extract local "b" on exprB: b=exprB; exprA(b)</li>
          <li>extract method "a" on exprA: b=exprB; a(b)</li>
          <li>inline local "b": a(exprB)</li>
        </ul>
        <p>Wouldn't it be great if this were part of the extract method refactoring? I.e. you get to choose
          subtrees of the expression's AST to form the parameters?
        </p>
        <p>Example at hand: my expression is "interestSet.get(ch)|op" and I want to extract a method "or(Integer a, int
          b)" where
          "interestSet.get(ch)" would form the first parameter. In the next step I would change the method to return
          "a == null ? b : a|b".
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#extract-method-reloaded</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#extract-method-reloaded"/>
    <a:updated>2007-10-04T16:15:00+02:00</a:updated>
  </a:entry>

  <a:entry>
    <a:title>Definite Initialization?</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="definite-initialization" href="#definite-initialization"></a>
        <p>
          The Java language specification requires that a call to a super(...) be the first statement in a constructor.
          That rule has often felt overly restrictive to me. For example, it forbids code like the following:
        </p>
        <pre>
          Constructor() {
          T local = expr;
          super(local);
          }
        </pre>
        <p>
          However super(expr) is allowed although both versions are provably equivalent. What's the motivation behind
          that rule? It's twofold: one, it garantuees that we do call a superclass constructor. Two, it (kind of)
          garantuees
          that we do not access "this" before that. The second point is kind of moot because the compiler still has to
          prove that
          "expr" does not access "this" either.
        </p>
        <p>
          The whole situation reminds me very much of definite assignment: with JDK 1.1, the rules
          for initialization of local final variables were relaxed. You do not need to provide an initialization
          expression at the point of declaration but you can assign a value later, iff the compiler can prove that a)
          you only assign once and b) you do not access the variable before.
        </p>
        <p>
          I personally believe :-) that the same relaxed rule could be applied to super constructor invocations. Take
          <a href="http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html">
            http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html</a>,
          replace the variable by "this", "definetely assigned" by "definetely initialized" and "assignment expression"
          by "super constructor
          invocation". Then the following code could be legal:
        </p>
        <pre>
          Constructor(x) {
          if(x != null) {
          super(x);
          } else {
          super();
          }
          }
        </pre>
        <p>
          Am I missing something?
        </p>
        <h3>Comments</h3>
        <div class="comment">
          <p>
            Matt: AFAIK, the JRE 1.4+ verifier allows super() to be later in the constructor, but only the language
            forbids it.
          </p>
          <p>In fact, for anonymous subclasses, the compiler generates assignments to this.static before calling
            super()! You can see evidence of this if you read through Lower.java in the compiler sources.
          </p>
        </div>
        <div class="comment">
          <p>
            <a href="http://chaoticjava.com/">Aviad Ben Dov</a>: I totally agree. This obscure rule has made a lot of
            code into a mess.
          </p>
          <p>Currently, to avoid having crazy expressions at the constructor, I create static methods and call those.
            But still, this causes ridiculous code.
          </p>
        </div>
        <div class="comment">
          <pre class="normal"><![CDATA[Robert Konigsberg: I'd love to see this restriction if only for precondition attribute validation.

Here's a contrived example:

class Derived extends Range {
 public Derived(int min, int max) {
   if (min > max) { throw new IAE(...); }
   super(min, max);
 }
}

Typically validations are single, such as

class Derived extends Range {
 public Derived(int min, int max) {
   super(min, max);
   if (min < 0) { throw new IAE(...); }
   if (max < 0) { throw new IAE(...); }
 }
}

This you can get away with using a validation method, but it's ugly.

class Derived extends Range {
 public Derived(int min, int max) {
   super(isNonNegative(min),
       isNonNegative(max));
 }
 private static int isNonNegative(int val) {
   if (val < 0) { throw new IAE(...); }
   return val;
 }
}

I'm not a language designer, but I'll ask: how about getting multiple return values? Then we could have

class Derived extends Range {
 public Derived(int min, int max) {
   super(validate(min, max));
 }
 private static int validate(int min, int max) {
   if (min < 0) { throw new IAE(...); }
   if (max < 0) { throw new IAE(...); }
   if (max < min) { throw new IAE(...); }
   return (min, max);
 }
}        ]]></pre>
        </div>
        <div class="comment">
          <p><a href="http://blogs.sun.com/brk">Bharath R</a>: In addition to the motivations that you mentioned, this
            rule also ensures that (in cases where explicit calls to super() are used) the subclass does not access
            non-static elements (methods and fields) of the super class before the latter has been completely
            initialized. Again, if the compiler can prove that this isn't violated, there is no need to mandate that
            super() be the first statement in the constructor.
          </p>
        </div>
        <div class="comment">
          <p><a href="http://weblogs.java.net/blog/forax/">Rémi Forax</a>: A simple rule could be:
          </p>
          <p>1) before super() or this(), context of the constructor is static
            so no access to an instance variable is allowed and "this" doesn't exist.
          </p>
          <p>2) after super()/this() context is classical</p>
          <p>Futhermore, only one super() or this() is allowed for an execution path.</p>

          Rémi
        </div>


      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#definite-initialization</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#definite-initialization"/>
    <a:updated>2007-09-29T12:50:00+02:00</a:updated>
  </a:entry>

  <a:entry>
    <a:title>On the Luxury of Walking to Work</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="on-the-luxury" href="#on-the-luxury"></a>
        <p>
          I've always enjoyed walking to the office on good weather (in Hamburg that means no rain), a habit that
          I'm determined to continue in Zurich. Here's a rocky rendition of my round about 25 minute commute, shot from
          the hip every ten seconds, stitched together with iMovie:
        </p>
        <p>
          <object width="425" height="350">
            <param name="movie" value="http://www.youtube.com/v/p5gVJXNVoUk"></param>
            <embed src="http://www.youtube.com/v/p5gVJXNVoUk" type="application/x-shockwave-flash" width="425"
                   height="350"></embed>
          </object>
        </p>
        <p>
          On a side note, I'm amazed how, let's say old fashioned the Youtube upload form is. Empty required fields are
          flagged only after
          submit/reload, the categories combo and my location map are reset in that moment. Not to mention that I have
          to invent yet another user name, even if I log in with my Google account - the obvious ones have already been
          harvested, of course.
        </p>
        <h3>Comments</h3>
        <div class="comment">
          <p>
            <a href="http://www.elien.de">Björn</a>: I expected to see something from Zürich and was quite astouned to
            recognize Hamburg after the first few frames. Only then, I realized that you are probably not even started
            your career in switzerland :)
          </p>
          <p>I wish you all the best and good luck.</p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#on-the-luxury</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#on-the-luxury"/>
    <a:updated>2007-09-12T19:35:00+02:00</a:updated>
  </a:entry>

  <a:entry>
    <a:title>New Adventures</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="new-adventures" href="#new-adventures"></a>
        <p>
          Friday was my last day at<a href="http://www.coremedia.com">CoreMedia</a>, after a long long time. I've had
          a great time and got to work with a bunch of people I highly respect. Fare well!
        </p>
        <p>
          Later this year, come find me in Google Zurich.
        </p>
        <p>
          <em>Folks, thanks for all the good wishes!</em>
        </p>
        <h3>Comments</h3>
        <div class="comment">
          <p>
            Sebastian Sanitz: Glückwunsch - Viel Spaß in Zürich!
          </p>
        </div>
        <div class="comment">
          <p>
            <a href="http://blogbauer.net">Björn Bauer</a>: Not only as a supporter I will miss you! Hope you feel good
            with Google. Wish you all the best!
          </p>
        </div>
        <div class="comment">
          <p>
            <a href="http://gafter.blogspot.com/">Neal Gafter</a>: Yay! Please look me up when you're in Mountain View.
          </p>
        </div>
        <div class="comment">
          <p>
            <a href="http://jandiandme.blogspot.com">Eberhard</a>: Well, I wish you the very best for your next step in
            your career. Zürich is quite a nice place - so enjoy
            your time there!
          </p>
        </div>
        <div class="comment">
          <p>
            <a href="http://blogs.sun.com/jmxetc">Daniel</a>: Hey Matthias, congratulations! -- daniel
          </p>
        </div>
        <div class="comment">
          <p>
            <a href="http://blogs.sun.com/brk">Bharath R</a>: Congratulations Matthias. Hope you keep the Java
            engineering flag flying high at Google (and continue your excellent writings). All the best.
          </p>
        </div>
        <div class="comment">
          <p>
            Gino: I wish you a good time in Zurich, please post the walk to your new work.
          </p>
        </div>
        <div class="comment">
          <p>
            Joerg: Alles Gute und guten Start!
          </p>
        </div>
        <div class="comment">
          <p>
            Jochen T: Awesome, Google sounds like it would be fun. They're turning evil though, so watch out. But then
            again, look at me -- I'm working for Microsoft ;-)
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#new-adventures</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#new-adventures"/>
    <a:updated>2007-09-09T10:40:00+02:00</a:updated>
  </a:entry>

  <a:entry>
    <a:title>R as in record</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="r-as-in-record" href="#r-as-in-record"></a>
        <p>
          Some interesting stuff I've been working on recently: the never ending story of object-relational mapping.
          Instead of breaking objects into relations, I've looked into mapping annotated classes directly onto
          <a href="http://download.oracle.com/docs/cd/B12037_01/appdev.101/b10807/10_objs.htm#CHDEFBEA">Oracle
            user-defined
            object types</a>, or basically records.
        </p>
        <p>
          What you get is: in combination with VARRAYS you get arbitrary nesting and can persist an object tree in a
          single
          column. It's about the same usage model as with XML serialization: if you can get used to non-cyclic,
          non-shared,
          trees of value objects you'll like it. Performance is great, on the order of several hundred items per second
          on
          a standard PC with Oracle/XE. In contrast to just serializing blobs, the database actually understands your
          schema and we can define indexes on simple properties or easily have the database server maintain
          index-organized
          tables for joining against property paths that may be array-valued. All important operations can be performed
          in single statements,
          no hidden roundtrips to maintain several tables or open/close lobs are necessary. (Actually not a 100% true,
          creating an instance of a struct requires to acquire a StructDescriptor first but that can be reused for all
          instances
          in the same batch).
        </p>
        <p>
          No object identity, no sessions to flush, no second-level cache: this is just about making the database
          understand
          structured complex values. I'm beginning to think of it as my JAXB for persistence.
        </p>
        <p>
          I would like to see this on other databases but the support for structs and arrays and their respective JDBC
          counterparts doesn't look great. On DB2, it seems like the path leads to their XML store anyway.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#r-as-in-record</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#r-as-in-record"/>
    <a:updated>2007-09-09T09:59:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Knee Jerk</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="knee-jerk" href="#knee-jerk"></a>
        <p>
          How simple-minded have I become? Patrick Logan holds a
          <a href="http://patricklogan.blogspot.com/2007/09/morse-codes-in-erlang.html">hammer</a>
          to my knee and my immediate jerk: "by no means does that pattern matching look particularly readable to me"
          and "I can do it just as well in Java". Although
          that is indeed the case, it isn't Patrick's point and I also thought I had long given up on contests like
          these.
          It must be some kind of allergy striking as soon as one topic becomes too popular. So just for your reference:
        </p>
        <pre><![CDATA[
  public static final Map<Character, String> codes = new HashMap<Character, String>() {
    {
      put('A', ".-"); put('B', "-..."); put('C', "-.-."); put('D', "-.."); put('E', ".");
      put('F', "..-."); put('G', "--."); put('H', "...."); put('I', ".."); put('J', ".---");
      put('K', "-.-"); put('L', ".-.."); put('M', "--"); put('N', "-."); put('O', "---");
      put('P', ".--."); put('Q', "--.-"); put('R', ".-."); put('S', "..."); put('T', "-");
      put('U', "..-"); put('V', "...-"); put('W', ".--"); put('X', "-..-"); put('Y', "-.--");
      put('Z', "--..");
    }
  };

  public static List<String> decode(String morse) {
    ArrayList<String> result = new ArrayList<String>();
    decode(morse, "", result);
    return result;
  }

  private static void decode(String morse, String partial, ArrayList<String> result) {
    if (morse.length() == 0) {
      result.add(partial);
    } else {
      for (Map.Entry<Character, String> entry : codes.entrySet())
        if (morse.startsWith(entry.getValue()))
          decode(morse.substring(entry.getValue().length()), partial + entry.getKey(), result);
    }
  }

  public static void main(String[] args) {
    System.out.println("decode(\".-\") = " + decode(".-"));
    System.out.println("decode(\"...---..-....-\").contains(\"SOFIA\") = " + decode("...---..-....-").contains("SOFIA"));
    System.out.println("decode(\"...---..-....-\").contains(\"SOPHIA\") = " + decode("...---..-....-").contains("SOPHIA"));
    System.out.println("decode(\"...---..-....-\").contains(\"EUGENIA\") = " + decode("...---..-....-").contains("EUGENIA"));
    System.out.println("decode(\"...---..-....-\").size() = " + decode("...---..-....-").size());
  }
]]></pre>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#knee-jerk</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#knee-jerk"/>
    <a:updated>2007-09-09T09:40:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Generics in Reflection</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="generic-reflection" href="#generic-reflection"></a>
        <p>
          Generics haven't really arrived in relective libraries yet. Most libraries reflect over class objects, not
          types. For example, while JAXB knows how to marshal a List&lt;X>, when presented a Holder&lt;X> it will
          reflect over the erased Holder.class and conclude that its value is of type Object, not X. Note to self:
          whenever designing a reflective library I will try and accept instances of Type from now on.
          <a href="http://gafter.blogspot.com/2006/12/super-type-tokens.html">Gafter's Gadget</a>
          will be helpful as the user's input device.
        </p>
        <p>Here's some handy code that helps you resolve member types in instantiations of generic types:</p>
        <pre><![CDATA[
  /**
   * Resolve the given type in the given environment. This entails
   * recursively replacing all type variables
   * referred to through by instantiations in env.
   *
   * @param type type of a member of a class in the inheritance tree of the env
   * @param env concrete instantiation of a (possibly parameterized) type
   * @return the resolved type
   */
  public static Type resolve(Type type, Type env) {
    ParameterizedType pt = cook(env);
    Type superclass = classOf(pt).getGenericSuperclass();

    if (superclass != null)
      type = resolve(type, superclass);

    for (Type genericInterface : classOf(pt).getGenericInterfaces())
      type = resolve(type, genericInterface);

    return replace(type, classOf(pt), pt.getActualTypeArguments());
  }

  private static Type replace(Type type, Class c, Type[] typeArguments) {
    if (type == null) return null;
    if (type instanceof TypeVariable) {
      int index = Arrays.asList(c.getTypeParameters()).indexOf(type);
      return index == -1 ? type : typeArguments[index];
    }
    if (type instanceof Class) return type;
    if (type instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) type;
      Type[] arguments = pt.getActualTypeArguments().clone();
      for (int i = 0; i < arguments.length; i++) {
        arguments[i] = replace(arguments[i], c, typeArguments);
      }
      return ParameterizedTypeImpl.make(classOf(pt), arguments, replace(((ParameterizedType)type).getOwnerType(), c, typeArguments));
    }
    throw new IllegalArgumentException(String.valueOf(type));
  }

  private static Class<?> classOf(ParameterizedType pt) {
    return (Class<?>) pt.getRawType();
  }

  private static ParameterizedType cook(Type t) {
    if (t instanceof ParameterizedType) return (ParameterizedType) t;
    if (t instanceof Class) {
      Class c = (Class) t;
      Type[] args = new Type[c.getTypeParameters().length];
      for (int i = 0; i < args.length; i++) {
        throw new UnsupportedOperationException("Can't (yet) construct a wildcard argument to " + t);
      }
      return ParameterizedTypeImpl.make(c, args, c.getEnclosingClass());
    }

    // have I missed a case?
    throw new IllegalArgumentException(String.valueOf(t));
  }
        ]]></pre>
        <p>
          Example: what type has iterator() in a LinkedList&lt;String>?
        </p>
        <pre><![CDATA[
    resolve(
      AbstractCollection.class.getMethod("iterator").getGenericReturnType(),
      parameterizedType(LinkedList.class, String.class)
    )

    =>

    java.util.Iterator<java.lang.String>
      ]]></pre>
        <p>
          Note that in their infinite wisdom, Sun have made the type hierarchy into interfaces with private
          implementations
          and you're invited to either re-implement them yourself or cross your fingers that
          <code>sun.reflect.generics.reflectiveObjects.*</code>
          is not gonna go away. A public concrete class in java.lang.reflect would have done the job, too, IMHO.
        </p>
        <h3>Comments</h3>
        <p>
          <a href="http://weblogs.java.net/blog/emcmanus">Eamonn McManus</a>
          @ 2007-08-02 04:38:06 PDT:
        </p>
        <div class="comment">
          <p>Excellent!</p>
          <p>Sergey Malenkov and I addressed a similar problem in the JDK. For JavaBeans (Sergey) and MXBeans (me), we
            needed the ability to know that the type of iterator() in a List&lt;String> is Iterator&lt;String>, etc. The
            result of our labours is the class com.sun.beans.TypeResolver in JDK7 (and OpenJDK), which you can see at
            https://openjdk.dev.java.net/source/browse/openjdk/jdk/trunk/j2se/src/share/classes/com/sun/beans/TypeResolver.java?view=markup
          </p>
          <p>There are actually quite a few nasties, of which the lack of concrete classes that you mention is one,
            though not too important for us inside the JDK. Another is doing the right thing in the presence of raw
            types (what is the type of iterator() in a raw List?). Also there's a bug in the way generic arrays are
            handled which means that you can get a GenericArrayType when it should really be a Class like
            String[].class.
          </p>
          <p>I was surprised to see that the spec for ParameterizedType doesn't say that you can modify the returned
            array. The good example of Method.getDeclaredAnnotations() and relations should be generalized. In practice
            it's hard to imagine that an implementation of ParameterizedType would not clone the array before returning
            it to you, so you don't really need to clone it again.
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#generic-reflection</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#generic-reflection"/>
    <a:updated>2007-07-31T10:40:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>The Easy ETag Issue</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="easy-etag" href="#easy-etag"></a>
        <p>
          <a href="http://www.dehora.net/journal/2007/07/earned_value.html">Bill de hÓra</a>:
        </p>
        <blockquote>
          "... Django will calculate an ETag for each request by MD5-hashing the page content, and it'll take care of
          sending Not Modified responses, if appropriate." That's it - you're done.
        </blockquote>
        <p>
          Just an observation: a Java web framework that collects all its output into a string before sending it
          to the client would be considered a poor, if not amateur implementation while we hail its Python competitor
          for it.
          Do Javanese have a premature optimization mindset? Indeed most Java projects never reach the point where they
          need to scale...
        </p>
        <p>
          How about this approach: in absence of a more efficient alternative, calculate the ETag as a streaming digest
          of the content and send it as a trailer field. Iff the client sent an If-None-Match, do the calculation first
          over the content streamed to /dev/null. If matched, send 304. If not matched, do it again, this time streaming
          to the client. In an MVC architecture, we could reuse the computed model and just repeat the rendering phase.
          This way we trade memory consumption against additional processing overhead.
        </p>
        <h3>Comments</h3>
        <p>
          <a href="http://d.hd.org/">Damon Hart-Davis</a>
          @ 2007-07-18 09:59:52 PDT:
        </p>
        <div class="comment">
          <p>...assuming that a page isn't very expensive to generate and is guaranteed to be generated exactly the same
            way twice.
          </p>
          <p>My largest app generates each (JSP) page on the fly each time, and it is very unlikely that the page
            content would be identical twice in a row (eg I drop some content if the page is taking too long to send to
            the user).
          </p>
          <p>On the other hand, generating an ETag on the fly is relatively easy, because I know the timestamps of the
            important constituents of the page.
          </p>
          <p>Thus: the 'run it twice' approach would for me be slow and wrong!</p>
          <p>
            <em>(Matthias) I absolutely agree (that's why I wrote "in absence...")! My proposal only tries to improve on
              the memory
              requirements of the out-of-the box solution people are wishing for so badly. The fundamental weaknesses
              remain: request must actually be performed in order to compute
              the ETag and it's based on the volatile rendered representation.
            </em>
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#easy-etag</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#easy-etag"/>
    <a:updated>2007-07-18T13:30:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Ids are forever ...</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="jroller-ids" href="#jroller-ids"></a>
        <p>
          ... until you decide to change them all. JRoller
          seems to just have done so:
          <img src="jroller.png" alt="150 unread items"/>
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#jroller-ids</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#jroller-ids"/>
    <a:updated>2007-07-17T18:30:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Maneifa Makes A NativE InterFAce</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="maneifa-native-binding" href="#maneifa-native-binding"></a>
        <p>
          So I had to interface with Windows' Lsa* APIs in order to retrieve
          the password of my machine domain account ("$machine.acc") that
          allows me to authenticate as the HOST/hostname kerberos service.
          No problemo. Downloaded the Python Win32 extensions and had the
          string out in like two minutes.
        </p>
        <p>
          Now do the same in Java. JNI is a no go. I looked at
          <a href="https://nlink.dev.java.net/">NLink</a>
          and found
          myself annotating most parameters with @MarshalAs(PVOID)
          and marshalling (e.g. LsaUnicodeString) in and out of ByteBuffers myself.
        </p>
        <p>
          Now don't get me wrong: I don't expect a native interface to implement the
          most wicked marshalling scheme for me. I would rather that it embraces marshalling
          on the Java side in an extensible fashion and only implements the absolute minimum
          in native code. So I came up with this for Win32:
        </p>
        <pre>
          /**
          * Push $words words from address $stack. Invoke $function.
          * After invocation, put the result at $stack. $retType defines
          * the result type (0: void, 1: 32bit int/ptr, 2: 64bit, 3: float,
          * 4: double. If $isCdecl, clear up the stack afterwards.
          */
          public static native void invoke(
          long function,
          long stack,
          int words,
          int retType,
          boolean isCdecl
          );
        </pre>
        <p>
          With the very first inline assembly code of my life it was easy to implement:
        </p>
        <pre>
          JNIEXPORT void JNICALL Java_org_mernst_maneifa_Maneifa_invoke
          (JNIEnv *env, jclass c, jlong function, jlong stack,
          jint words, jint retType, jboolean isCdecl)
          {
          int i, w;
          int *buf = (int*) stack;
          void (*f)() = (void (*))function;

          for(i=words-1; i>=0; i--) {
          w = buf[i];
          __asm push w
          }

          switch(retType) {
          case 0: ((void (_stdcall *)())f)(); break;
          case 1: buf[0] = ((int (_stdcall *)())f)(); break;
          case 2: ((long long *)buf)[0] = ((long long (_stdcall *)())f)(); break;
          case 3: ((float*)buf)[0] = ((float (_stdcall *)())f)(); break;
          case 4: ((double*)buf)[0] = ((double (_stdcall *)())f)(); break;
          }

          if(isCdecl) {
          for(i=0; i&lt;words; i++) {
          __asm add esp, 4
          }
          }
          }
        </pre>
        <p>
          Easy enough. EVERYTHING ELSE CAN BE DONE IN JAVA. Well, almost.
          Three things I need are there but weren't public: ClassLoader#findNative finds
          symbols in DLLs, DirectByteBuffer#address and new DirectByteBuffer(address, cap)
          do the pointer fiddling.
        </p>
        <p>
          For a different architecture this interface might need to be different (wrt registers) but that's ok.
          It reminds me of the approach SWT takes in contrast to AWT: instead of mapping a uniform
          interface to the system in tedious native code, rather use your high-level language.
        </p>
        <p>
          Once it's settled down a little, I might describe what interfaces I use for marshalling. Now it's time for
          lunch.
          Oh, as for the name: Maneifa used to work here at CoreMedia.
        </p>
        <p>
          <em>Update:</em>
          a MacOS/X Intel port was easy enough. Removed _stdcall and added stack padding.
        </p>
        <h3>Comments</h3>
        <p>
          <a href="http://gestalt.monoid.net">Michael Nischt</a>
          @ 2007-07-11 23:15:14 PDT:
        </p>
        <div class="comment">
          <p>
            Definitely nice!
            <br/>
            I'd love to see some usage examples soon..
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#maneifa-native-binding</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#maneifa-native-binding"/>
    <a:updated>2007-07-11T13:01:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Generics and Delegation</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="generics-and-delegation" href="#generics-and-delegation"></a>
        <p>
          <a href="http://tech.puredanger.com/2007/07/03/pattern-hate-template/">Alex</a>
          hates template methods
          and I think he's right. I prefer delegation, too, but traditionally it has a drawback: the delegate's
          type is obscured. In Alex' example, I have to cast to the specific ConnectionFactory type if I wanted to
          use one of its specific methods. That's why I've started to parameterize delegating classes with the
          type of their delegates like so:
        </p>
        <pre>public class ConnectionPool
          <b>&lt;CF extends ConnectionFactory></b>
          {
          public final
          <b>CF</b>
          connectionFactory;
          public ConnectionPool(CF connectionFactory, ...) { ... }
          ...
          }

          public interface ConnectionFactory { ... }
        </pre>
        <p>
          Now a client can have a<code>CountingConnectionFactory</code>, and use it into a pool without casting:
          <code>pool.connectionFactory.numberOfCreatedConnections</code>.
        </p>
        <p>If you don't care about the specific type, just use a<code>ConnectionPool&lt;?></code>. Actually maybe the
          compiler/IDE shouldn't be so picky about raw usage of (especially bounded) parameterized types and just
          be happy with
          <code>ConnectionPool.</code>
          <a href="http://gafter.blogspot.com/2007/07/constructor-type-inference.html">Neal's</a>
          call for type inference for constructors would help to make construction more concise, too.
        </p>
        <p>You may have also noticed the use of a
          <code>public final</code>
          field. I don't quite see the point of hiding
          information that my client provided in the first place (ducking and covering).
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#generics-and-delegation</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#generics-and-delegation"/>
    <a:updated>2007-07-07T14:41:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Bytecode Instrumentation for Jist</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="bytecode-instrumentation-jist" href="#bytecode-instrumentation-jist"></a>
        <p>
          I've added some bytecode instrumentation support to
          <a href="#Get-the-Jist">Jist</a>
          using the always excellent
          <a href="http://asm.objectweb.org/">ASM</a>
          library.
          <code>Agent#instrument(class, methodName, n)</code>
          returns an
          <code>Activity</code>
          that enters and exits as the method is called/returns. Example:
        </p>
        <pre><![CDATA[Aggregation
  .ofDurationOf(Agent.instrument(Thread.class, "run"));
]]></pre>
        <p>
          This code will aggregate statistical data about Thread lifetimes. Unfortunately this code contains some
          problems: it uses Instrumentation#redefineClasses and thus does not interoperate well with other
          instrumentation agents.
          Since Jist only pushes aggregation data every once in a while, thread-local event data may be lost
          when a thread exits. I guess I should inject a forced publish at thread exit and/or add a forcePublish flag to
          an event.
        </p>
        <h3>Comments</h3>
        <p>Alan @ 2007-07-01 09:30:39 PDT:</p>
        <div class="comment">
          <p>Have you looked at retransformClasses? It was added in Java SE 6 to support multiple agents doing BCI.</p>
          <p>
            <em>(Matthias) I have but unfortunately I'm on a Mac. I guess I should download the old old Mustang build
              that Apple provides...
              or look at Parallels and an OpenSolaris Image.
            </em>
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#bytecode-instrumentation-jist</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#bytecode-instrumentation-jist"/>
    <a:updated>2007-07-01T15:06:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Gmail goes Web 1.0</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="gmail-oldschool" href="#gmail-oldschool"></a>
        <p>
          Just pressed "send" and got greeted with "your connection
          to gmail has expired. please log in again". Mail lost. Me seriously grumpy.
          I've had this type of UI with Outlook Web Access long enough.
        </p>
        <h3>Comments</h3>
        <p>Lee @ 2007-07-01 19:59:29 PDT:</p>
        <div class="comment">
          <p>have you looked in your 'drafts' folder?</p>
          <p>
            <em>(Matthias) Thanks, I have. It contains an old draft that doesn't help.</em>
          </p>
        </div>
        <p>
          <a href="http://crazybob.org/">Bob Lee</a>
          @ 2007-07-14 09:19:25 PDT:
        </p>
        <div class="comment">
          <p>When this happens, I log in in a different window, and then I can send the message.</p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#gmail-oldschool</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#gmail-oldschool"/>
    <a:updated>2007-06-29T15:28:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>ariadna for Windows x64?</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="ariadna-winx64" href="#ariadna-winx64"></a>
        <p>
          I'm always happy to hear that someone is using<a href="http://www.mernst.org/ariadna">ariadna</a>.
          Now Neil Ferguson is asking for a Windows x64 build of the agent dll which I cannot provide.
          Can someone help out? Thanks in advance.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#ariadna-winx64</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#ariadna-winx64"/>
    <a:updated>2007-06-26T22:28:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Bad Refactoring</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="bad-refactoring" href="#bad-refactoring"></a>
        <p>
          Case of a refactoring gone bad:
        </p>
        <pre>
          <b>public volatile</b>
          ByteBuffer<b>message</b>;

          public ByteBuffer getMessage() {
          return duplicate(<b>message</b>);
          }

          private ByteBuffer duplicate(ByteBuffer message) {
          return (message != null) ? message.duplicate() : null;
          }
        </pre>
        <p>
          IDEA 7.0M1b will happily inline
          <code>#duplicate</code>
          so that it
          reads
          <code>#message</code>
          twice (<a href="http://www.jetbrains.net/jira/browse/IDEA-13304">Bug</a>):
        </p>
        <pre>
          public ByteBuffer getMessage() {
          return (
          <b>message</b>
          != null) ?<b>message</b>.duplicate() : null;
          }
        </pre>
        <p>
          Always watch your tool!
        </p>
        <h3>Comments</h3>
        <p>
          <a href="http://d.hd.org/">Damon Hart-Davis</a>
          @ 2007-06-18 04:11:33 PDT:
        </p>
        <div class="comment">
          <p>Yuck!</p>
          <p>Now that's really bad, especially with the huge red warning light that is 'volatile'!</p>
          <p>Rgds</p>
          <p>Damon</p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#bad-refactoring</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#bad-refactoring"/>
    <a:updated>2007-06-18T10:35:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Google Groups Virus Detector</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="google-groups-virus-detector" href="#google-groups-virus-detector"></a>
        <p>
          Anyone else get this? I got it on two independent computers now, one Mac, one PC.
          Of course I can't say for sure my computer isn't 0wned but it looks bogus to me.
        </p>
        <img src="sorry.png" alt="Google Error Message"/>
        <h3>Comments</h3>
        <p>
          <a href="http://www.tutorials.de">Thomas Darimont</a>
          @ 2007-06-13 05:32:58 PDT
        </p>
        <div class="comment">
          <p>jep, I also see this message when I browse the guice-google group...
            May be google just want us to solve some Captchas for them ;-)
          </p>

          <p>As in: Human Computation: http://video.google.com/videoplay?docid=-8246463980976635143</p>

          <p>Best regards,
            <br/>
            Tom
          </p>
        </div>
        <p>
          <a href="http://www.elien.de">Björn</a>
          @ 2007-06-14 00:47:12 PDT
        </p>
        <div class="comment">
          <p>Question is, what's meant by "[..] or your network is infected". Eventually you're part of the internet!
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#google-groups-virus-detector</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#google-groups-virus-detector"/>
    <a:updated>2007-06-13T14:10:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Partial APPdates</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="partial-appdates" href="#partial-appdates"></a>
        <p>
          <a href="http://www.snellspace.com/wp/?p=683">James Snell</a>
          and
          <a
            href="http://www.dehora.net/journal/2007/06/app_on_the_web_has_failed_miserably_utterly_and_completely.html">
            Bill de hÓra
          </a>
          point to the PATCH method to handle partial updates of Atom entries through APP. I don't see that need. PUT
          with the If-Match: header is just enough to do the work
          on the client side using optimistic concurrency control. The server side patch model:
        </p>
        <pre>
          Client Server
          --- GET(uri) -->
          &lt;-- ETag, entry ---
          <em>prepare patch</em>
          --- PATCH(uri, patch) -->
          <em>with locked entry
            apply(patch, entry)
          </em>


        </pre>

        can easily be replaced by this:

        <pre>
          Client Server
          --- GET(uri) -->
          &lt;-- ETag, entry ---
          <em>prepare patch
            do
            newEntry = apply(patch, entry)
          </em>

          --- PUT(uri, newEntry, If-Match: etag) -->
          <em>with locked resource
            compare tag ? update : fail
          </em>
          &lt;-- 200 OK or 412 Precondition Failed ---
          <em>if(Precondition Failed)</em>
          --- GET(uri) -->
          &lt;-- ETag, entry ---
          <em>while(Precondition Failed)</em>


        </pre>
        <p>
          The second version requires the same number of roundtrips if there is no conflict and we assume that
          you always read an entry before patching it. Optimistic concurrency control breaks down when you have
          heavy concurrent updates on the same entry, something I'd argue to be rather uncommon. It does require
          the client to handle the patching but I don't think this is an undue burden.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#partial-appdates</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#partial-appdates"/>
    <a:updated>2007-06-10T11:40:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Mobile TV Interop Event</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="mobile-tv-interop-event" href="#mobile-tv-interop-event"></a>
        <p>
          We just spent a great week in Berlin at the BMCO Test Camp to
          test interoperability of OMA BCAST Mobile TV implementations.
          Results cannot be disclosed but I can say it was an amazing event.
          Engineers from all over the world brought handsets, encoders,
          scramblers, smartcards, key management components
          and whatnot in emulation, prototype up to product quality, together with
          assorted IDEs, debuggers, analyzers, flashing equipment. And for
          a broadcasting event, way too many cables :-) Most participants demonstrated
          a great spirit of cooperation and were
          eager to help each other, running high on adrenaline to get their systems to interoperate.
        </p>
        <p>
          Some observations: my NIO/multicast hack has run rock-solid for days except for one VM freeze.
          Hot Swapping is a real winner during testing. It's sad to see people programming ad-hoc HTTP clients
          in C (on a server!) - of course it didn't work. In a stark contrast to Java One, almost noone brought a Mac.
          Some people can go for days with almost no sleep (not me).
        </p>
        <p>
          We are very happy with our results. German engineering paid off! Plus we had a lot of fun.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#mobile-tv-interop-event</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#mobile-tv-interop-event"/>
    <a:updated>2007-06-08T10:46:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Type Operators</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="type-operators" href="#type-operators"></a>
        <p>
          I was talking to someone about the type system of Tycoon2, our research language back in school, and I
          mentioned
          it had a higher order type system with type operators. So they asked me what are type operators good for. And
          I couldn't say.
        </p>
        <p>
          Today I could think of something. I often wish for a Map whose key and value types aren't fixed but instead
          dependent
          on one another. Example: an XmlTypeSystem contains a map from class objects to marshallers. Given a Class&lt;T>
          I can get a Marshaller&lt;T>. Signature:
          <br/>
          <code>&lt;T> Marshaller&lt;T> getMarshaller(Class&lt;T> clazz)</code>.
        </p>
        <p>
          Trying to implement this method using a hashmap I cannot get away without a compiler warning since
          <br/>
          <code>Map&lt;Class&lt;?>, Marshaller&lt;?>> marshallerByClass</code>
          <br/>
          is the best I can come up with in Java.
        </p>
        <p>
          So actually I would like a Map with a signature like this:
        </p>
        <pre>
          interface DMap&lt;T, KeyOperator extends &lt;T>Object, ValueOperator extends &lt;T>Object> {
          &lt;K extends T> ValueOperator&lt;K> get(KeyOperator&lt;K> key);
          }

          // or rather
          interface DMap&lt;T,
          KeyOperator extends &lt;? super T>Object,
          ValueOperator extends &lt;? super T>Object>


        </pre>
        <p>
          To be read as such: A DMap is parameterized by a base type T and two type operators that map any type
          below T to a subtype of Object. The get method is parameterized by a type K below T and maps between the
          application of the first type op to the application of the second. This way we can assign a meaningful
          type to our marshaller map:
        </p>
        <pre>
          DMap&lt;Object, :T=>Class&lt;T>, :T=>Marshaller&lt;T>> marshallerByClass;

          // explicit type arguments for demonstration purposes only
          marshallerByClass.&lt;String>get(String.class) => Marshaller&lt;String>
          marshallerByClass.&lt;Feed>get(Feed.class) => Marshaller&lt;Feed>
        </pre>
        <p>
          So this is what type operators can be good for. I do not think they have a broad application though and I do
          NOT
          propose we do anything like this to Java.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#type-operators</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#type-operators"/>
    <a:updated>2007-05-30T09:09:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Comments</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="comments" href="#comments"></a>
        <p>
          I've finally added some crude Response-O-Matic backed comment forms to my blog.
          Even though they're moderated I hope this lowers the entry barrier for you.
          Keep them rolling in!
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#comments</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#comments"/>
    <a:updated>2007-05-28T13:04:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Cascading: First Patch</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Cascading-First-Patch" href="#Cascading-First-Patch"></a>
        <p>
          Here's a first patch against b13 that survives simple tests. A number
          of problems remain:
        </p>
        <ul>
          <li>It only cascades method invocations with explicit receiver expressions. Javac does not
            explicitly compute the receiver at typecheck time for implicit this or outer this targets
            and so does not have their types ready.
          </li>
          <li>super.m() has the type of the superclass, not of this.</li>
        </ul>
        <pre>
          <b>--- comp/Attr.java.orig.txt 2007-05-26 13:55:53.000000000 +0200
            +++ comp/Attr.java 2007-05-26 14:15:51.000000000 +0200
          </b>
          <![CDATA[@@ -1315,6 +1315,18 @@
                               restype.tsym);
             }
+            // as a special case, o.m() where m is a void method, has type of o
+            if(restype == Symtab.voidType && !isStatic(TreeInfo.symbol(tree.meth))) {
+                if(tree.meth.tag != JCTree.SELECT) {
+                    log.warning(tree.meth.pos(), "Cannot (yet) cascade unqualified method call");
+                } else {
+                    JCExpression receiver = ((JCFieldAccess) tree.meth).selected;
+                    restype = receiver.type;
+                }
+            }
+
+
+
             // Check that value of resulting type is admissible in the
             // current context.  Also, capture the return type
             result = check(tree, capture(restype), VAL, pkind, pt);]]>

          <b>--- comp/TransTypes.java.orig.txt 2007-05-26 13:56:46.000000000 +0200
            +++ comp/TransTypes.java 2007-05-26 14:15:51.000000000 +0200
          </b>
          <![CDATA[@@ -583,7 +587,8 @@
         tree.args = translateArgs(tree.args, argtypes, tree.varargsElement);

         // Insert casts of method invocation results as needed.
-        result = retype(tree, mt.getReturnType(), pt);
+        // mernst: do not use mt.resType as cascading may have changed it
+        result = retype(tree, types.erasure(tree.type), pt);
     }

     public void visitNewClass(JCNewClass tree) {]]>

          <b>--- jvm/Gen.java.orig.txt 2007-05-26 14:00:07.000000000 +0200
            +++ jvm/Gen.java 2007-05-26 14:16:38.000000000 +0200
          </b>
          <![CDATA[@@ -1664,14 +1664,24 @@
  *************************************************************************/

     public void visitApply(JCMethodInvocation tree) {
+
        // Generate code for method.
        Item m = genExpr(tree.meth, methodType);
+
+        // in case of a cascade, duplicate the receiver
+        boolean cascaded = ((MethodType)tree.meth.type).restype == Symtab.voidType && tree.type != Symtab.voidType;
+        Item stackItem = cascaded ? items.makeStackItem(tree.type) : null;
+        if(cascaded) stackItem.duplicate();
+
        // Generate code for all arguments, where the expected types are
        // the parameters of the method's external type (that is, any implicit
        // outer instance of a super(...) call appears as first parameter).
        genArgs(tree.args,
                TreeInfo.symbol(tree.meth).externalType(types).getParameterTypes());
        result = m.invoke();
+
+        // in case of a cascade, the receiver is top of stack now
+        if(cascaded) result = stackItem;
     }

     public void visitConditional(JCConditional tree) {]]>
        </pre>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Cascading-First-Patch</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Cascading-First-Patch"/>
    <a:updated>2007-05-26T14:21:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Cascading: A Modest Language Proposal</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="AModestLanguageProposal" href="#AModestLanguageProposal"></a>
        <p>
          I've hinted at this
          <a href="http://www.mernst.org/blog/rss.xml#How-Far-is-Fidji">before</a>
          - a discussion
          with my colleague
          <a href="http://www.3plus4.de/">Stefan Aust</a>
          brought the topic back up: I'm proposing to add cascading
          for non-static method invocations of type void to the Java language.
        </p>
        <h3>Informal Discussion</h3>
        <p>
          I propose to make invocations of void methods usable as expressions. The type of a method invocation
          <code>o.m(args)</code>
          where m resolves to a void method would not be void but instead the type of o.
          The result of the method invocation could either be returned, be assigned to a variable, be used as
          a method argument, or be the target of another method invocation. Cascaded method invocations
          of void methods, especially of property setters would be possible:
        </p>
        <pre>final JFrame jFrame = new JFrame()
          .setBounds(100, 100, 100, 100)
          .setVisible(true);
        </pre>
        <p>
          Implementation: the change can be implemented solely by changing the way javac compiles method invocations.
          This
          is advantageous because no old code needs to be recompiled: after computing the receiver, it is simply
          duplicated
          on the stack. Either it is used as the result value or it is discarded as in JLS 14.8 "Expression Statements".
        </p>
        <h3>Required Specification Changes</h3>
        <p>
          JLS 15.12.2.6 Method Result and Throws Types: the type of a method invocation expression needs adjustment. The
          different forms of method invocation need to be discussed - either the type of the receiver expression, this
          or
          outer this.
        </p>
        <p>
          JLS 15.12.4.1 Compute Target Reference (If Necessary): append "if the method returns void and there is a
          target reference,
          the target reference is retained and will become the result value".
        </p>
        <p>
          There seems to be no wording about the result value in 15.12.4.5 "Create Frame, Synchronize, Transfer
          Control".
        </p>
        <h3>Required Compiler Changes</h3>
        <p>
          I don't have the code handy (just browsing) and it looks like two small changes to Gen#visitApply (Gen.java)
          and to
          MemberItem#invoke (Items.java) should be enough.
          <i>Update:</i>
          I forgot the necessary change to the type checker:
          that should be TransTypes#visitApply (TransTypes.java).
        </p>
        <h3>Conclusion</h3>
        <p>
          So far, a void method invocation can only be used as an expression statement, so
          the semantics of existing valid code remain unchanged. Setter invocation orgies
          can now be made a little nicer.
        </p>
        <p>
          If I find time I'll try my first KSL hack.
          What do you think?
        </p>
        <h3>Comments</h3>
        <p>
          <a href="http://weblogs.java.net/blog/forax/">Rémi Forax</a>
          @ May 23, 2007 8:19 PM:
        </p>
        <div class="comment">
          <p>Hi matthias,</p>
          <p>the typechecker of javac is implemented in Attr
            and not in TransTypes.
            Transtypes pass does the erasure (and some tricks like
            inserting inner class backreference etc.)
          </p>

          <p>cheers,
            Rémi
          </p>
        </div>
        <p>Anonymous @ 2007-05-31 09:57:01 PDT</p>
        <div class="comment">
          <p>Thats a feature I've thought about too. It seems really logical and can't break old code. There is one
            disadvantage though. The documentation of the signature sends contradictory signals. And anyway, imagine a
            immutable class. No use there since that already should do what you propose, but in a mutable class, things
            can get strange. Is that method returning this, or another object? Not immediately apparent.
          </p>
        </div>
        <p>
          <a href="http://reuse.sourceforge.net">Peter Kehl</a>
          @ 2007-06-18 03:00:24 PDT:
        </p>
        <div class="comment">
          <p>This looks good and usefull.</p>
          <p>RE Anonymous - immutable objects: Any methods on immutable objects that return void won't modify the object
            (by the definition of immutable). So any void method won't have any side effects on the this object.
          </p>
          <p>Then it's 100% legit to have a sequence of such void calls, and cascading them makes sense. Of course, void
            methods on immutable object won't do a big deal to the object itself - they may either validate the object
            or register it in some static/threadlocal structures.
          </p>
          <p>You may have a setter/modification method on an immutable object, but that method must return a new object
            based on this. So the method won't return void - therefore void cascading won't apply to it.
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#AModestLanguageProposal</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#AModestLanguageProposal"/>
    <a:updated>2007-05-22T23:28:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Wave Particle --- Particle Wave?</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="WaveParticleParticleWave" href="#WaveParticleParticleWave"></a>
        <p>
          Ever so often I'm utterly confused over a design choice. Two alternative designs
          flipping back and forth in my mind with their respective pros and cons and I loathe
          wasting time over them. Other people are much more pragmatic. Examples in no
          particular order:
        </p>
        <dl>
          <dt>Embedding vs Embedded</dt>
          <dd>Be a webapp or embed Jetty? Is the primary purpose
            of your app to speak HTTP or does it just happen to?
          </dd>
          <dt>Synchronization vs Active Object</dt>
          <dd>Thinking of it I couldn't really name you
            a reason to submit tasks to an object instead of having the relevant method synchronized - you have the
            same set of challenges and actually extra context switches.
            Nonetheless pooled-thread-per-object looks attractive and simple.
          </dd>
          <dt>Mutable Object vs Replacement</dt>
          <dd>Instead of changing an object under synchronization I like setting
            up and dropping in a replacement instead which can often be done through a volatile write. Of
            course that means the parent must be mutable and thus the question repeats at a different level.
          </dd>
          <dt>Remote Service vs Multiply Installed Jar</dt>
          <dd>Redundancy is dangerous. A domain rule should not be implemented twice - but does that mean that
            only one component in my distributed system may "physically" contain it? Or is it "ok" to have the same jar
            in many places? Can I promise to update it everywhere? Versioning of algorithms may help.
          </dd>
          <dt>Multithreaded Service vs Decicated Objects</dt>
          <dd>For those how aren't afraid of garbage collection anymore:
            how do you choose? service.service(parameters) vs instance.service()? Oh, more confusion: Spring scopes make
            it easy to inject a proxy representing a "current" entity into a singleton. So service could have a field
            representing the "current context". Ugh.
          </dd>
          <dt>instance.destroy() vs factory.destroy(instance)</dt>
          <dd>More general: object.doIt() vs service.doItTo(object)</dd>
          <dt>NIH vs dependency hell</dt>
          <dd>Is byteArrayToHexString worth a dependency? What if it uses a different logging
            framework?
          </dd>
        </dl>
        <p>
          I could go on forever... Are there other examples you're getting grey hairs about? Many of these have been
          discussed before under various names. Obviously, the pattern books don't have an answer either. They
          just describe the alternatives more eloquently. I guess the truth is: you just have to choose and it helps to
          be
          consistent throughout one piece of software. Maybe you know better afterwards.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#WaveParticleParticleWave</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#WaveParticleParticleWave"/>
    <a:updated>2007-05-05T18:02:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>DLR</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="DLR" href="#DLR"></a>
        <p>
          Microsoft announces<a
          href="http://blogs.msdn.com/hugunin/archive/2007/04/30/a-dynamic-language-runtime-dlr.aspx">DLR</a>,
          the Dynamic Language Runtime. More details to come so stay tuned on Jim's blog. If I'm not mistaken it's a
          pure user-space
          implementation right now that tries to standardize functionality required for implementations of dynamic
          language interpreters.
          Once those interfaces stabilize Microsoft could go ahead and implement optimizations below in future CLR
          versions.
        </p>
        <p>
          A crucial one of these optimizations, namely VM support for dynamic method invocations, was postulated by
          Gilad Bracha in<a href="http://jcp.org/en/jsr/detail?id=292">JSR 292</a>.
          Bears the question, what ever happened to this JSR? Can we expect to hear any more in this direction?
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#DLR</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#DLR"/>
    <a:updated>2007-05-01T21:02:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>JavaOne Secrets</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="JavaOne-Secrets" href="#JavaOne-Secrets"></a>
        <p>
          Some time it's always gonna be the first time, and this year I'm going to have my JavaOne initiation. So I
          built my session schedule and I'm hoping to turn some of my digital encounters into real ones. If you want to
          meet up, too, or have any tips for the best experience and be it "bring your own sandwich" I would be more
          than glad. Thanks and see you there!
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#JavaOne-Secrets</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#JavaOne-Secrets"/>
    <a:updated>2007-04-27T23:31:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Wieder Runterkommen</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Just-what" href="#Just-what"></a>
        <p>
          Blood pressure once again at 180. Just who wants to punish me...
        </p>
        <h3>Exhibit A</h3>
        <pre><![CDATA[
try {
  ... new DataFlavor("text/uri-list;class=java.lang.String") ...
} catch (ClassNotFoundException e) {
        ]]></pre>
        A constructor with a java.lang.Class argument wouldn't harm.
        <em>Update:</em>
        to make things worse, there's a "fix by extension"
        available: "javax.activation.ActivationDataFlavor is a special subclass
        of java.awt.datatransfer.DataFlavor that allows to set all three values
        stored by the DataFlavor class via a new constructor." Thanks to
        <a href="http://weblogs.java.net/blog/forax/">R&#x00E9;mi</a>
        (for
        the pointer, not the implementation!).

        <h3>Exhibit B</h3>
        <pre><![CDATA[
try {
  ... DataTypeFactory.newInstance().newDuration(...) ...
} catch (DatatypeConfigurationException e) {
        ]]></pre>
        I wonder when we'll finally get an SPI for implementing java.lang.Integer.

        <h3>Exhibit C (fixed in Java 6)</h3>
        <pre><![CDATA[
try {
  ... "string".getBytes("UTF-8") ...
} catch (UnsupportedEncodingException e) {
        ]]></pre>
        I bet that people who understandably avoid this extra cruft
        are responsible for half of all encoding errors, the other half being those who
        do not understand encoding. Oh didn't someone want to build
        <a
          href="https://jdk-collaboration.dev.java.net/servlets/ProjectForumMessageView?messageID=13166&amp;forumID=1463">
          CharSet#UTF8()</a>?

        <h3>Epilogue</h3>

        If you do decide to use checked exceptions,
        <em>please</em>
        go the extra way
        and provide alternatives that are statically known not to throw.
        Adrenaline is bad for my health. Blogging helps a little, and this:

        <pre><![CDATA[
// ... it's like closing the window to the street
<T> T mute({=>T throws Exception} block) {
  try {
    return block.invoke();
  } catch(RuntimeException e) {
    throw e;
  } catch(Exception e) {
    throw new RuntimeException(e);
  }
}
        ]]></pre>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Runterkommen</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Runterkommen"/>
    <a:updated>2007-04-20T18:31:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Annotations are not the API</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Annotations-are-not-the-API" href="#Annotations-are-not-the-API"></a>
        <p>
          My 2cents towards<a href="http://weblogs.java.net/blog/kohsuke/archive/2007/04/annotaitonmockb.html">mocked
          annotations</a>:
          when designing a library, always design a proper model in plain old classes. Make
          this model a public API and your library a runtime that interprets model instances.
          Use annotations only as a shorthand, as metadata from which a model instance
          can be derived. But leave the door open for alternative, programmatic access.
        </p>
        <p>
          For example, an experimental XML binding API I've played with exposes things like the following:
        </p>
        <pre><![CDATA[
XmlComplexType<V>: binding of a complex type to java objects of type V
JavaProperty<P,C>: getting/setting values of type C into an object of type P
XmlComplexTypeBinding<P, C>: binding of instances of complex type C into parent instances of type P
...
        ]]></pre>
        <p>
          Apart from the programmatic aspect, I find that this model is the most precise way to document
          how the library works. (JAXB does have a model but it's hidden away as implementation detail).
          My XML binder will never be as complete or stable as JAXB or do XML mapping any "better" but it lays
          its cards open about how exactly it bridges between XML and Java.
        </p>
        <p>
          Of course, this all applies just as well to other forms of configuration but we already knew that ...
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Annotations-are-not-the-API</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Annotations-are-not-the-API"/>
    <a:updated>2007-04-11T09:54:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Oh those swedish product names</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Those-Swedish-Product-Names" href="#Those-Swedish-Product-Names"></a>
        <p>This one might not sell as good.</p>
        <p>
          <img src="fartyg.jpg" alt="fartyg"/>
        </p>

        <div class="comment">
          <p><i>Johan Liesén</i>: Just wanted to let you know that "fartyg" is the Swedish word for ship
            or large boat.
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Those-Swedish-Product-Names</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Those-Swedish-Product-Names"/>
    <a:updated>2007-03-28T23:55:00+02:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Scrolling and Paging</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Scrolling-and-Paging" href="#Scrolling-and-Paging"></a>
        <p>Scrolling and paging: both well accepted and useful forms of visiting an amount of data bigger than your
          screen. What
          drives me nuts is that they are often employed in the same application. Click-scroll-click-scroll until I'm
          steaming. Microsoft Outlook Web
          Access, Google Mail, Google Search, my Xing contact list are all guilty of that. Letting me configure how many
          items I
          want per page is a poor replacement for what I really want: show as many items as fit, stupid. Second worst
          crime, by the way: changing the
          position of the "next" button from page to page.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Scrolling-and-Paging</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Scrolling-and-Paging"/>
    <a:updated>2007-03-27T19:33:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Ferm&#x00E9; pour travaux</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Ferme-au-travaux" href="#Ferme-au-travaux"></a>
        <p>
          <a href="http://www.musee-fernandleger.fr/">Mus&#x00e9;e national Fernand L&#x00e9;ger</a>, Biot,
          <a href="http://www.antibes-juanlespins.com/fr/culture/musees/picasso/">Mus&#x00e9;e Picasso</a>, Antibes,
          <a href="http://www.musee-matisse-nice.org/">Mus&#x00e9;e Matisse</a>, Nice. At least we got some sun.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Ferme-au-travaux</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Ferme-au-travaux"/>
    <a:updated>2007-03-27T19:30:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Pattern, transient final, serialization</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Pattern-transient-final-serialization" href="#Pattern-transient-final-serialization"></a>
        <p>
          I tried to find a better fix for
          <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6436458">Bug ID: 6436458</a>
          that would eliminate synchronization altogether. Basically it boils down to the problem of serializing
          transient final fields. In this case some fields of the Pattern class hold the compilation information of the
          regex that we don't want
          serialized but rather reconstructed on deserialization. But we can't assign them in #readObject since they're
          final.
          And we want them final so that Pattern is<a
          href="http://www-128.ibm.com/developerworks/java/library/j-jtp03304/#4.0">initialization safe</a>.
          Sounds like a Catch-22.
        </p>
        <p>
          The solution is #readResolve. We can deserialize an intermediate Pattern instance that holds the pattern
          string
          and the flags - the transients being null - and then resolve it to a compiled instance using Pattern#compile.
          #readResolve is not recursive,
          so we won't end up in an infinite loop.
        </p>
        <pre><![CDATA[public class Pattern implements Serializable {
  private final String pattern;
  private final int flags;
  private transient final ...;

  public static Pattern compile(String pattern, int flags) {
    return new Pattern(pattern, flags);
  }

  private Pattern(String pattern, int flags) {
    this.pattern = pattern;
    this.flags = flags;
    this ... = ...;
  }

  private Object readResolve() {
    return Pattern.compile(pattern, flags);
  }
}]]></pre>
        <p>
          Mission accomplished: initialization safety, slim serialized form and no synchronization altogether.
          <a
            href="https://jdk-collaboration.dev.java.net/servlets/ProjectForumMessageView?messageID=19086&amp;forumID=1463">
            Patch</a>.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Pattern-transient-final-serialization</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Pattern-transient-final-serialization"/>
    <a:updated>2007-03-14T17:00:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Get the Jist</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Get-the-Jist" href="#Get-the-Jist"></a>

        Toying with dtracing Java apps through JNI was fun but had a number of downsides:
        <ul>
          <li>it would only run on Solaris</li>
          <li>I had to jump through JNI hoops</li>
          <li>there was only one probe</li>
          <li>I only had strings</li>
          <li>D is not exactly good for building abstractions. I found myself repeating a lot of
            <code>...-entry { self->x[y]=... }</code>
            boilerplate.
          </li>
        </ul>

        <p>
          So I'm trying a new approach: Jist, Java InSTrumentation. It is heavily DTrace inspired but completely
          implemented in Java, as a simple 55k no-dependency jar. With Jist, you can define low overhead probes in your
          code that can be dynamically
          enabled at runtime. As with DTrace, probes are merely the source of information - you define separately
          how you want to aggregate the data and correlate probes that were written by independent authors and just
          happen
          to run in the same code path. Probes and aggregation functions are thoroughly typed.
        </p>
        <p>
          In comparison to DTrace, what is Jist not ? It only captures what happens in the JVM, it does not come
          with all-purpose providers like syscall, it is not easily invoked from the outside on an arbitrary Java
          process
          (agent attachment notwithstanding) and there is no garantueed safety from misbehaving aggregations.
        </p>
        <h2>Defining and Firing Probes</h2>
        In contrast to DTrace, Jist distinguishes two kinds of probes: activities and events. Activities span an
        interval in the program execution, and can be nested; the stack of activity contexts is managed by Jist. This is
        very
        similar to the -entry and -return convention in DTrace where you often build contexts in a thread-local map.
        Events on the other hand are just points in the program execution. Both types of probes can signal detail data.
        This is how you define and use probes:
        <pre><![CDATA[
class Server {
  public static final Activity<String> Request = new Activity<String>("Request");

  public void handle(String request) {
    Request.enter("request");
    try {
      ...
    } finally {
      Request.exit();
    }
  }
}

class ConnectionPool {
  public static final Event<DataSource> ConnectionOpened = new Event<DataSource>("ConnectionOpened");

  {
    ...
    ConnectionOpened.fire(dataSource);
  }
}
        ]]></pre>

        <p>
          When an activity starts, a Context record is allocated and pushed onto the thread-local stack. As of now,
          there is now way to disable this, but I have the feeling that this cost is negligable in most cases -
          otherwise
          I'll employ a small thread-local cache. Events
          on the other hand are disabled by default. Every time an event fires it checks for enabledness through a
          volatile
          - this should be ok for most cases. As with logging, in case the event argument is expensive to compute, you
          can check beforehand:
          <code>if(ConnectionOpened.isEnabled()) ...</code>
          .
        </p>
        <h2>Simple Aggregation</h2>
        One of the cornerstones of DTrace is in-place aggregation. Instead of saving all instrumentation data for
        offline aggregation, you condense the data as much as possible in place and save only the aggregated data.
        Especially, an aggregation function should have the property that you can feed it data piecemeal: Count,
        Average,
        Sum, are all examples of such functions. Jist, like DTrace, capitalizes on the aggregation function property
        in that it aggregates incrementally in the moment an event happens, and especially, it aggregates events
        thread-locally.
        Less frequently, the thread-local aggregation values are aggregated into a global view. Both incremental and
        thread-local
        aggregation ensure that the instrumentation overhead stays low. An example: the following code defines an
        aggregation
        that will simply count how many times a connection was opened:
        <pre><![CDATA[
Aggregation<?, Long> aggregation = Aggregation.of(Count.ofEvents, ConnectionPool.ConnectionOpened);
aggregation.enable();
while (true) {
  Thread.sleep(1000);
  System.out.println(aggregation);
}
        ]]></pre>
        <p>
          On #enable, the aggregation will attach itself as a listener on the Event. When the event fires, it is
          routed to the aggregation which will increment a thread-local counter. Only sometimes will the counter
          be propagated to the global counter. In that codepath we only have one volatile-get (read listeners), two
          invoke-interface, a
          thread-local get and a counter increment. Every once in a while do we push the counter onto a
          ConcurrentLinkedQueue.
          On my MacBook (two threads repeatedly firing events, 1.8Ghz Core2Duo, -server) that amounts to:
        </p>
        <pre><![CDATA[
number of events (updated each ConnectionOpened) = 0
number of events (updated each ConnectionOpened) = 38947105
number of events (updated each ConnectionOpened) = 38512126
number of events (updated each ConnectionOpened) = 40150689
number of events (updated each ConnectionOpened) = 39189567
        ]]></pre>
        <p>40 million events per second amounts to 100 cycles per event, a number that stays stable at 20 threads, too.
          That's pretty good.
        </p>

        <h2>Correlation</h2>
        <p>
          Now, incrementing counters is not especially interesting and can be done more easily. It gets more interesting
          to correlate
          different, independent probes. For example, we would like to know the number of connection openings
          <em>per request uri</em>
          .
          For that, we can employ a Mapping aggregation function:
        </p>
        <pre><![CDATA[
Aggregation<?, Map<String, Long>> aggregation =
  Aggregation.of(Mapping.of(Server.Request, Count.ofEvents), ConnectionPool.ConnectionOpened);

number of events by Request (updated each ConnectionOpened) = {/uri2=2285635, /uri1=4571279}
number of events by Request (updated each ConnectionOpened) = {/uri2=1833648, /uri1=3667297}
number of events by Request (updated each ConnectionOpened) = {/uri2=1842779, /uri1=3685558}
number of events by Request (updated each ConnectionOpened) = {/uri2=1974581, /uri1=3949161}
        ]]></pre>
        <p>
          This shows the real potential: we can see that requests to /uri1 open twice as many connections as those to
          /uri2. That's something
          no profiler and no DTrace will tell you. Another teaser (numbers highly dubious):
        </p>
        <pre><![CDATA[
Aggregation<?, Map<String, Statistics.Data>> aggregation =
  Aggregation.of(Mapping.of(Server.Request, Statistics.of(Duration.of(Server.Request))), Server.Request.Exit);

statistics for duration in NANOSECONDS of Request by Request (updated each exit from Request) =
  {/uri2={|sample|=1615081, sum=7.43407E8, min=0, max=64524000, avg=460.29084609378725, stddev=96321.15405584917},
   /uri1={|sample|=1615084, sum=9.26188E8, min=0, max=75908000, avg=573.4611945880214, stddev=123748.53849281174}}
statistics for duration in NANOSECONDS of Request by Request (updated each exit from Request) =
  {/uri2={|sample|=1602764, sum=9.54039E8, min=0, max=100171000, avg=595.246087384044, stddev=145823.88277769994},
   /uri1={|sample|=1602763, sum=8.40672E8, min=0, max=77095000, avg=524.5142294899496, stddev=118100.06216280891}}
...
      ]]></pre>

        <h2>Outlook</h2>
        <p>
          One of the perks of DTrace is that you can attach to a process and run D scripts that were not compiled
          into that process. I'm still pondering how to do that. A scripting solution for the definition of aggregations
          might be interesting, one that is defined on dynamically loaded agents or something JMX-based. Right now,
          you'll have to bake in aggregations and export them somehow, i.e. though JMX. Some simple class-redefinition
          to inject probes into foreign code would be nice, too.
        </p>
        <p>
          To some extent I hope that aggregation of independent events will reduce the time you spend sorting log
          records together
          (".. ok, here it starts .. now lets look for the same thread, ok down here, ... go up one page again").
        </p>
        <h2>Get it</h2>
        <p>
          Now that you're mouthwatering enough, go download Jist
          <a href="/jist">here</a>.
          Or get the most recent version:
          <code>hg clone static-http://mernst.org/jist</code>
          .
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Get-the-Jist</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Get-the-Jist"/>
    <a:updated>2007-03-04T12:24:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Experience comes with age</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Experience-comes-with-age" href="#Experience-comes-with-age"></a>
        <p>
          Germany's facing fierce resistance about moving the retirement age up to 67. Sun
          thinks a little more progressively in this context :-)
        </p>
        <p>
          <img src="fiftyfive.png" alt="Years of experience: 55"/>
        </p>
        <p>
          Anyone? http://www.sun.com/corp_emp/search.cgi?req=548725&amp;p=
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Experience-comes-with-age</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Experience-comes-with-age"/>
    <a:updated>2007-02-03T15:38:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>SDT probes for Java</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="SDT-probes-for-Java" href="#SDT-probes-for-Java"></a>
        <p>
          The real power of
          <a href="http://www.opensolaris.org/os/community/dtrace/">DTrace</a>
          lies in its ability to correlate independently provided data in ways unforeseen by
          the developer. Too often have I been asked things like "nice cache eviction statistics but how can I see which
          algorithm, query, user is responsible for this?". D is the SQL of instrumentation: it enables ad-hoc queries
          over unprepared data.
        </p>
        <p>
          As of today,
          <a href="http://java.sun.com/javase/6/docs/technotes/guides/vm/dtrace.html">DTracing Java</a>
          is cool as long
          as you're doing relatively general performance analysis of the software - questions
          about "which method?", "which class?", "which monitor?" can be answered - to open the ultimate insight into
          application
          space ("which query?", "which dataset?", "which url?") we need to work a little harder.
        </p>
        <p>
          I'm interested in two kind of probes: the ones that establish a thread-local context for a possibly lengthy
          period, i.e. "starting request to /url", "starting transform foo.xsl", "importing x" and the corresponding
          exit
          in order to correlate these with events such as "evicting y" or "creating temp-file z".
        </p>
        <h3>A simple DTrace provider for Java applications</h3>
        <p>
          So I want to do something like this (obviously not in one class):
        </p>
        <pre><![CDATA[
  static final dtrace.DTraceContext<String> REQUEST = new dtrace.DTraceContext<String>("request");
  static final dtrace.DTraceContext<String> TEMPLATE = new dtrace.DTraceContext<String>("template");
  static final dtrace.DTraceContext<String> EL = new dtrace.DTraceContext<String>("el");

  public static void main(String[] args) throws Exception {
    while(true) {
      REQUEST.push("/index.html");
        TEMPLATE.push("outer.jsp");
          // do some real work here
          TEMPLATE.push("inner.jsp");
            EL.push("${something.wild}");
            EL.pop("${something.wild}");
          TEMPLATE.pop();
          // do some real work here
        TEMPLATE.pop();
      REQUEST.pop();
      Thread.sleep(1000);
    }
  }
	]]></pre>

        <p>
          The DTraceContext class looks as follows. It does some stack management and ultimately fires entry and
          exit events through JNI:
        </p>
        <pre><![CDATA[
  public class DTraceContext<T> {
    private static native void init();
    private static native void fireEntry(String name, Object top, Object previous);
    private static native void fireReturn(String name, Object top, Object previous);

    public final String name;
    private final ThreadLocal<ArrayList<T>> value = new ThreadLocal<ArrayList<T>>() {
      protected ArrayList<T> initialValue() {
	return new ArrayList<T>(5);
      }
    };

    public DTraceContext(String name) {
      this.name = name;
    }

    public T get() {
      ArrayList<T> ts = value.get();
      return ts.isEmpty() ? null : ts.get(ts.size()-1);
    }

    public void push(T value) {
      T previous = get();
      this.value.get().add(value);
      fireEntry(name, value, previous);
    }

    public void pop() {
      ArrayList<T> values = this.value.get();
      T value = values.remove(values.size() - 1);
      fireReturn(name, value, get());
    }

    static {
      System.loadLibrary("dtracecontext");
      init();
    }
  }

  JNI code:

  // error checking yadda yadda
  JNIEXPORT void JNICALL Java_dtrace_DTraceContext_fireEntry
    (JNIEnv *env, jclass class, jstring name, jobject top, jobject previous)
  {
    if(DTRACECONTEXT_ENTRY_ENABLED()) {
      const jbyte *namestr = (name==NULL) ? NULL : (*env)->GetStringUTFChars(env, name, NULL);

      jobject tops = (top==NULL) ? NULL : (*env)->CallObjectMethod(env, top, tostring);
      const jbyte *topstr = (tops==NULL) ? NULL : (*env)->GetStringUTFChars(env, tops, NULL);

      jobject previouss = (previous==NULL) ? NULL : (*env)->CallObjectMethod(env, previous, tostring);
      const jbyte *previousstr = (previouss==NULL) ? NULL : (*env)->GetStringUTFChars(env, previouss, NULL);

      DTRACECONTEXT_ENTRY(namestr, topstr, previousstr);

      if(previousstr != NULL) (*env)->ReleaseStringUTFChars(env, previouss, previousstr);
      if(previouss != NULL) (*env)->DeleteLocalRef(env, previouss);

      if(topstr != NULL) (*env)->ReleaseStringUTFChars(env, tops, topstr);
      if(tops != NULL) (*env)->DeleteLocalRef(env, tops);

      if(namestr != NULL) (*env)->ReleaseStringUTFChars(env, name, namestr);
    }
  }

  // ... same for pop
  ]]></pre>
        <p>
          Note how the native methods take Objects but the probes carry strings:
          I do a callback to #toString and extract the UTF-8 sequences only after checking whether the probe is enabled.
          The overhead of the JNI calls for disabled probes seems good if not used in tight loops (like 22 ns per call
          on my machine) - if it turns out to be a problem I'll need to hoist the test into the Java code. The
          DTRACECONTEXT_ENTRY is a macro
          generated by dtrace from my provider description - see
          <a href="http://blogs.sun.com/tpenta/entry/dtrace_using_placing_sdt_probes">"statically defined tracing"</a>
          - basically we compile a call to a dummy external C function into our code, and postprocess it with dtrace
          that will
          patch this code sequence in order to disable/enable the probe. The provider:
        </p>
        <pre>
          provider dtracecontext {
          // args (contextname, context entered, previously active context)
          probe ENTRY(char *, char *, char *);
          // args (contextname, context left, context returned to)
          probe RETURN(char *, char *, char *);
          };
        </pre>
        <p>
          A note to the naming: I tried to name the probes "entry" and "return" first - I thought they would be
          recognized
          by the "-F" (indent flow) option of dtrace but unfortunately that is not so; and return is a dtrace keyword.
          So
          the first thing that came to my mind was capitalization - I will most probably change that.
        </p>
        <p>
          You will have noticed that this provider is very static - there's only two probes for the whole Java
          process and the actual type comes as a string argument. All application probes are disabled and enabled
          together which will have a bigger performance impact - maybe I can come up with some dynamic
          compilation/library
          generation scheme later.
        </p>
        <p>
          I haven't collected really good examples from real software yet - that's why there were no actual dtrace
          scripts
          in action but I hope you could see the possibilities. I think the potential is huge. The demise of logging?
          That would be too good to be true...
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#SDT-probes-for-Java</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#SDT-probes-for-Java"/>
    <a:updated>2007-02-03T12:45:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Euphemism of the Day</a:title>
    <a:content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a name="Euphemism-of-the-Day" href="#Euphemism-of-the-Day"></a>
        <p>
          "HTML allowed" actually means "Comply with those angle brackets or I will swallow all your paragraphs. You
          have been warned.".
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Euphemism-of-the-Day</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Euphemism-of-the-Day"/>
    <a:updated>2007-01-17T17:21:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Solaris 10 Privileges</a:title>
    <a:content type="xhtml">
      <div>
        <a name="Solaris-10-Privileges" href="#Solaris-10-Privileges"></a>
        <p>
          The Solaris 10 kernel supports a fine-grained security model, based on
          <a href="http://www.sun.com/bigadmin/features/articles/least_privilege.html">"least privilege"</a>
          .
          For example, in order to run a server on port 80 you don't need to be root. The PRIV_NET_PRIVADDR privilege is
          sufficient.
        </p>
        <p>
          The same applies to coniguration of the IPsec security associations and policy entries. Unfortunately,
          the respective command line tools 'ipseckey' and 'ipsecconf' do check for uid 0 before they even try
          to talk to the kernel.
        </p>
        <p>
          Luckily, w/ Open Solaris being open source I could quickly fix that. Commented out the checks, did the
          ppriv thing, et voila, a normal user with SYS_NET_CONFIG can now do what I want. Neat!
        </p>
        <p>
          <em>
            Update: I've learnt that I shouldn't use privileges for that directly (will become messy over time)
            but rather a profile that defines the right execution attributes such as the "Network Security" profile. Yet
            that profile doesn't work right now for the outlined reasons (bug filed). Workaround: use your own profile
            and exec_attr with uid=0. No need to recompile the tools - just assign that profile to your user.
          </em>
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Solaris-10-Privileges</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Solaris-10-Privileges"/>
    <a:published>2007-01-17T17:20:00+01:00</a:published>
    <a:updated>2007-02-03T12:49:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Atom in Style</a:title>
    <a:content type="xhtml">
      <div>
        <a name="Atom-in-Style" href="#Atom-in-Style"></a>
        <p>
          WARNING: this is an experiment and may well wreak havoc on your blog-reading experience.
        </p>
        <p>
          I'm cheap and lazy and thus I'm not willing to pay for PHP hosting nor would I want to administer
          a blog system. Yet I want to host my blog on my own domain. I've been using Thingamablog until
          now but their editor has serious limitations, especially when working with pre-formatted code fragments.
          And I can only edit the blog from the one machine where the database is.
        </p>
        <p>
          I have thus changed my blog to one major source file in the Atom format. I'm typing this entry directly
          in atom format into IDEA's XML editor - I have a nice live template to insert the minimum scaffolding.
          When I finish, this source file is then only post-processed (w/ JAXB) to derive &quot;updated&quot;, &quot;link&quot;,
          &quot;id&quot;
          and &quot;a&quot; elements (a process that I could still do by hand if that little piece of Java code is not
          handy).
          I have left all old ids intact and hope that they won't be re-syndicated, even if the
          feed format changes from RSS to Atom (this file will still be called rss.xml).
        </p>
        <p>
          No HTML is generated, the feed is directly styled with CSS, not even XSL. A nice learning experience and
          the capabilities of CSS continue to impress me. As a potential downside, I'm now
          including all my posts in one file. Certainly more than before but not too huge if all participants make use
          of the relevant HTTP mechanisms.
        </p>
        <p>
          I've tried to be as standards compliant as possible but your mileage with various readers may vary:
        </p>
        <ul>
          <li>Firefox renders this feed best. I had to include a lengthy comment header in order to actually enable the
            stylesheet.
          </li>
          <li>IE 7 fairs worst. It won't use the stylesheet (someone? DOCTYPE?) but is fooled by the comment. So you'll
            only see the text() nodes.
          </li>
          <li>
            <i>(Fixed)</i>
            Both Omea Reader and Google Reader have issues with &quot;bleeding&quot; anchor tags (&lt;a../&gt;).
            Obviously they're embedding the XHTML pretty directly into quirks HTML without reprocessing it.
          </li>
          <li>RSS Bandit and BottomFeeder look fine.</li>
          <li>Syndication to PlanetJDK has stopped :-(</li>
        </ul>
        <p>
          The CSS element selectors don't seem to care about namespaces. I don't know whether this will continue to work
          with
          <a href="http://www.w3.org/TR/css3-namespace/">CSS3 Namespace Module</a>
          .
        </p>
        <p>
          The sidebar on the right is implemented as a dedicated feed entry that is styled differently.
        </p>
        <p>
          So much from the low-end side of blog software - please let me know what problems you're having and
          whether they prohibit you from reading this journal any longer. Enhancements to the stylesheet are welcome,
          too.
          You know where you can find it.
        </p>
      </div>
    </a:content>
    <a:id>http://mernst.org/blog/rss.xml#Atom-in-Style</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Atom-in-Style"/>
    <a:updated>2007-01-16T23:37:00+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Maybe it's time to think a little further</a:title>
    <a:content type="xhtml">
      <div>
        <a name="Maybe-its-time-to-think-a-little-further" href="#Maybe-its-time-to-think-a-little-further"></a>
        <p>
          If you're bored of the &quot;property&quot; word, please skip.
        </p>
        <p>
          If not, you may note that some of the REST principles apply to
          properties:
        </p>
        <p>
          We expect to read a property without visibly affecting the object.
          Reading properties is supposed to be a
          <i>safe operation</i>
          . We also
          expect setting the same value for a second time to have no tangible
          effect. Setting properties is supposed to be
          <i>idempotent</i>
          . The
          values we see from properties may or may not be the actual state of an
          object, they are merely a
          <i>representation</i>
          .
        </p>
        <p>
          In a distributed, concurrent environment, atomicity also is of concern.
          I feel progressively unsure about using an array of setter invocations
          for reconfiguration of a service, e.g. through JMX. The REST way of
          PUTting an entire representation of the -desired- resource's state looks
          a lot safer to me. It gives the object a chance to implement atomicity.
          Recently, we built a service that is reconfigurable through PUTting an
          entire configuration document, and this approach feels really solid
          compared to fine grained remoted JMX-based management. The admin UI
          operates not on the object but on a representation of its state and then
          submits it to take effect.
        </p>
        <p>
          What is my point? I believe that applying REST principles to OO
          programming lends itself to separate the &quot;life&quot; objects with their logic
          from &quot;dumb&quot; state representations that can be manipulated or bound to.
          We might not want to bind UI elements directly to property methods. We
          might rather go and implement representations through simple structs w/
          fields that are also nicely transported, persisted, versioned, ...
          Putting that state into side-effects would be of no concern at this
          stage. Useful linguistic support would be compile-time checked field
          references so we can bind some UI element to a field of the state
          representation.
        </p>
        <p>
          There's a ton of open questions - no question about that. And this may
          be a pile of bull. But thinking about how representations (external
          ones, too), state, binding, ... all fit together is definetely a larger
          topic than just syntactic sugar around field declarations.
        </p>
        <div class="comment">
          <p>
            <i>Comment by Eamonn McManus @ Jan 15, 2007 2:58 PM:</i>
          </p>
          <p>
            <i>Atomicity and JMX</i>
          </p>
          <p>
            Hi Matthias,
          </p>
          <p>
            Re your entry &quot;May it's time to think a little further&quot;, indeed I think
            configuring a JMX object with a sequence of setAttribute operations is
            suboptimal. There are a few ways to avoid this within the JMX API:
          </p>
          <ul>
            <li>
              As of Java SE 6, you can use an MXBean with a single complex attribute
              representing the collection of values to set. This is basically a
              &quot;struct&quot;. Because it is mapped to a standard Java type (CompositeData)
              the potential problems with versioning and serialization are reduced.
            </li>
            <li>
              In earlier versions you can still use the MBeanServer.setAttributes
              operation to set a bunch of attributes at the same time. But there's
              no way to require that the attributes all be set together, and there's
              some work needed to make the set atomic. It doesn't have to be very
              much work though, for instance using
              <a href="http://blogs.sun.com/nickstephen/entry/jmx_atomic_access_to_multiple">this
                idea
              </a>
              from Nick Stephen.
            </li>
            <li>
              An alternative to both of the above is to have an MBean operation
              rather than an attribute, the parameters to which are the values to
              set. This means there's no longer a way to set just some of the
              values, which overcomes the chief drawback of the preceding approach;
              it also works better with management consoles such as JConsole than
              either of the two alternatives. The operation can be called
              setSomething without ambiguity.
            </li>
          </ul>
          <p>
            I'm not sure how this fits into the wider debate about properties,
            though. I think the questions that arise when setting things remotely
            are distinct from the questions that arise for local objects, though
            they do overlap. In particular the idea of extending the JavaBeans
            conventions so you can have a setter that sets more than one thing seems
            interesting. One of the advantages of immutable objects is that you
            can't get an inconsistent object state by an unfortunate combination of
            setters, but the same advantage could be had by only providing setters
            that set enough properties to retain consistency.
          </p>
        </div>
      </div>
    </a:content>
    <a:id>http://www.mernst.org/blog/archives/01-01-2007_01-31-2007.html#151</a:id>
    <a:link href="http://www.mernst.org/blog/rss.xml#Maybe-its-time-to-think-a-little-further"/>
    <a:updated>2007-01-16T20:51:30.345+01:00</a:updated>
  </a:entry>
  <a:entry>
    <a:title>Aren't properties objects?</a:title>
    <a:content type="xhtml">
      <div>
        <a name="Arent-properties-objects" href="#Arent-properties-objects"></a>
        <p>
          Surface syntax aside, implementation-wise a property is all object-like
          and I'm surprised we're still talking generating methods according to a
          naming convention. A property *has* setter and getter, it can be
          referenced, especially in order to bind it to a UI component, you can
          attach listeners, ...
        </p>
        <p>
          <a href="http://st-www.cs.uiuc.edu/users/brant/papers/ValueModel/ValueModels.htm">ValueModel</a>
          anyone?
        </p>
        <pre>
          public final RWProperty&lt;String&gt; name = new Slot&lt;String&gt;();

          mernst.name.get();
          mernst.name.set(&quot;matthias&quot;);
          mernst.name.attachListener(...);
          label.bind(mernst.name);
        </pre>
        <div class="comment">
          <p>
            <i>Comment by Stephen Colebourne @ Jan 13, 2007 7:28 PM:</i>
          </p>
          <p>
            Hi,
          </p>
          <p>
            See my blogs about this
            <br/>
            <a href="http://www.jroller.com/page/scolebourne?entry=java_7_property_objects">
              http://www.jroller.com/page/scolebourne?entry=java_7_property_objects
            </a>
            <br/>
            <a href="http://www.jroller.com/page/scolebourne?entry=mo