Monday, February 09, 2009

LISP: There and Back Again

What a delightful essay on Clojure with more cognoscenti-revealing references than you can shake a stick at.

Friday, February 06, 2009

Speeding up Cygwin login

On Windows I use Cygwin extensively. So I open a lot of login shells. However these shells are sometimes slow to load, especially when my host is busy with other jobs.

While editing my ~/.bash_profile I noticed code like this:

if [ -d "some path element" ]; then
    PATH="some path element:$PATH"
fi

This is a common idiom. However, it is making a separate fork to /bin/test every time.

A simple improvement:

if [[ -d "some path element" ]]; then
    PATH="some path element:$PATH"
fi

A little trying it out and the verdict: Wow, big improvement.

Tuesday, January 27, 2009

Distributed OSGi: a caution by Roger Voss

Not a new article, but made newly relevant to me as I begin planning a new, distributed project, Roger Voss has sage words in Distributed OSGi - Tilting at Windmills: Don't do it. But if you are going to do it, take precautions.

I have heard the same advice all my career starting with C and UNIX, yet Roger can still point out how often non-veteran developers founder between Scylla and Charybdis.

KDE on Windows

Try KDE 4.2 on Windows. Do it for the children.

Monday, January 26, 2009

Stumbled on: GuiceyFruit

While trying out mvnbrowser I stumbled on GuiceyFruit, a value-add to Guice by James Strachan and Willem Jiang (no blog?).

GuiceyFruit hits the right notes for me: integration of Guice into lots of nice places, especially that EJB3/J2EE business some of my coworkers talk about. Spring-to-Guice converter is cute.

And a bonus: a nice Maven repo tracking Guice 2.x development.

Friday, January 23, 2009

Formatter and new machines

Why is this code broken?

public class Stringifier {
    private final DateFormatter formatter = new SimpleDateFormatter("YYYMMDD");

    public String toYYYMMDD(final Date date) {
        return formatter.format(date);
    }
}

Here's the fixed code which makes the answer obvious:

public class Stringifier {
    private final DateFormatter formatter = new SimpleDateFormatter("YYYMMDD");

    public String toYYYMMDD(final Date date) {
        synchronized(formatter) {
            return formatter.format(date);
        }
    }
}

I checked recently and the lowest-powered servers my company buys have 8 cores. There is no such thing as single-threaded code. See the bug now?

Thursday, January 22, 2009

BDD v. TDD: an example

Following up on my last post, one of my secondary goals in talking about fluent interfaces for testing in Java is to showcase the difference between a traditional TDD approach and a BDD approach:

// In SamTest.java
@Test
public void testIsVisibleAfterGettingTheOneRingAndWearingIt() {
    sam.getItems().add(THE_ONE_RING);
    try {
        THE_ONE_RING.setWorn(true);
    } catch (final GameOverManException ignore) {
    }
    assertThat(sam.isVisible(), is(false));
}

// In TheOneRingTest.java:
@Test(expected = GameOverManException.class)
public void testSetWornForSam() {
    new Sam().getItems().add(THE_ONE_RING);
    THE_ONE_RING.setWorn(true);
}

Contrast:

// In WhenPossessingTheOneRing.java:
@Test
public void samShouldBeInvisibleAfterWearingIt() {
    assertThat(sam().after().gettingTheOneRing().and().puttingItOn(), is(
            not(visible())));
}

@Test
public void samShouldNeverWearIt() {
    assertThat(sam().after().gettingTheOneRing().and().puttingItOn(), is(
            corrupted()));
}

(Given, of course, a suitable fluent testing DSL. Opinion question: I put the DSL in PosessingTheOneRing.java and followed the convention of naming the support class by dropping When from the test class name. Is this good practice?)

Monday, January 19, 2009

Presenting at Houston Tech Fest

I have been invited to fill in for a last minute speaker cancellation at Houston Techfest. I will be presenting this coming Saturday (Jan 24) at 10:15am on the UH main campus.

My presentation is entitled, Fluent Interfaces for Testing in Java, something I worked with Rod Coffin on at work.

I did have different titles originally; it was an iterative process to settle on this one. Previous titles:

  • LOTRO in a Nutshell - too dated
  • LOTRO in Action - too fashionable
  • LOTRO for Dummies - copyright issues

I hope to see some familiar faces on Saturday! Sample code for the talk:

public class WhenPossessingTheOneRing {
    @Test
    public void frodoShouldBeInvisibleAfterWearingIt() {
        assertThat(frodo().after().gettingTheOneRing().and().puttingItOn(),
                is(not(visible())));
    }

    @Test
    public void gandalfShouldNeverGetIt() {
        assertThat(gandalf().after().gettingTheOneRing(),
                is(corrupted()));
    }

    @Test
    public void samCanGetIt() {
        assertThat(sam().after().gettingTheOneRing(),
                is(not(corrupted())));
    }

    @Test
    public void samShouldBeInvisibleAfterWearingIt() {
        assertThat(sam().after().gettingTheOneRing().and().puttingItOn(),
                is(not(visible())));
    }

    @Test
    public void samShouldNeverWearIt() {
        assertThat(sam().after().gettingTheOneRing().and().puttingItOn(),
                is(corrupted()));
    }
}

Friday, January 09, 2009

@Ignore still has life

A nicely thought out post from Ben Rady why @Test(expected = AssertionError.class) is better than @Ignore for JUnit 4 failed tests.

Two reasons I still like @Ignore:

  1. @Ignore includes a string parameter which I use to explain why the test is ignored. It really stands out.
  2. My editor and maven both make special note of ignored tests, and I can find uses of @Ignore to easily jump to any ignored tests.

Demonstrating the first point:

@Ignore("Ship broken in release 1.2.3, fix for next release")
@Test
public void testSign() {
    assertThat(fixture.compute(123), is(not(lessThan(0))));
}

The best choice still remains: Fix the test.

UPDATE: I thought about this more and Ben has a point I overlooked: by expecting {@code AssertionError}, it is true you lose in clarity and documentation compared to {@Ignore}, but the test will start failing once the original problem is fixed:

@Test(expected = AssertionError.class)
public void testSignIsBroken() {
    assertThat(fixture.compute(123), is(not(lessThan(0))));
}

Now you can go and write a proper test against the fixed code.

Thursday, September 25, 2008

Hamlet D'Arcy's "Declarative Synchronization with Java 5's ReadWriteLock"

Hamlet D'Arcy posts on declarative synchronization with Java combining JDK4 proxies, JDK5 concurrency and Groovy, a very slick conjunction of technologies. Plus Hamlet is a cool name.

UPDATE: It is simple enough to translate the Groovy into pure Java (with a class rename and factory method along the way):

public class ReentrantHandler
        implements InvocationHandler {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    private final Object target;

    public static <T> T newReentrantProxy(final Class<T> itf, final T impl) {
        return itf.cast(newProxyInstance(impl.getClass().getClassLoader(),
                new Class<?>[]{itf}, new ReentrantHandler(impl)));
    }

    private ReentrantHandler(final Object target) {
        this.target = target;
    }

    public Object invoke(final Object proxy, final Method method,
            final Object[] args) {
        try {
            final Method targetMethod = target.getClass().getMethod(
                    method.getName(), method.getParameterTypes());

            if (targetMethod.isAnnotationPresent(WithReadLock.class)) {
                lock.readLock().lock();
                try {
                    return targetMethod.invoke(target, args);
                } finally {
                    lock.readLock().unlock();
                }
            } else if (targetMethod.isAnnotationPresent(WithWriteLock.class)) {
                lock.writeLock().lock();
                try {
                    return targetMethod.invoke(target, args);
                } finally {
                    lock.writeLock().unlock();
                }
            } else {
                return targetMethod.invoke(target, args);
            }
        } catch (final Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

Tuesday, September 23, 2008

Finding cyclic calls with state: Google Collections

I found a clever way to detect cyclic calls in Google Collections:

  private static class MemoizingSupplier<T>
      implements SerializableSupplier<T> {
    private final Supplier<T> delegate;
    private MemoizationState state = MemoizationState.NOT_YET;
    private T value;

    public MemoizingSupplier(Supplier<T> delegate) {
      this.delegate = delegate;
    }
    public T get() {
      switch (state) {
        case NOT_YET:
          state = MemoizationState.COMPUTING;
          try {
            value = delegate.get();
          } finally {
            state = MemoizationState.NOT_YET;
          }
          state = MemoizationState.DONE;
          break;
        case COMPUTING:
          throw new CyclicDependencyException();
      }
      return value;
    }
    private static final long serialVersionUID = 1138306392412025275L;
  }

I doubt it is original, but I have not run across this combining of cycle detection with memoizing before. That probably says more about me than Google.

Thursday, September 11, 2008

Serializing an interface into a work queue

Using the work queue idiom and JDK4 proxies, one can automate serializing calls into an interface:

public class FacadeFactory<T> {
   private final Class<T> interfaz;
   private final BlockingQueue<Frame> queue;
   private final ExecutorService pool;

   public FacadeFactory(final Class<T> interfaz,
           final BlockingQueue<Frame> queue, final ExecutorService pool) {
       this.interfaz = interfaz;
       this.queue = queue;
       this.pool = pool;
   }

   public T facade(final T delegate) {
       pool.submit(new Callable<Void>() {
           public Void call() {
               final List<Frame> work = new ArrayList<Frame>();

               for (; ;) {
                   try {
                       work.add(queue.take());
                   } catch (final InterruptedException e) {
                       currentThread().interrupt();
                       return null;
                   }
                   queue.drainTo(work);

                   for (final Frame frame : work)
                       frame.apply(delegate);

                   work.clear();
               }
           }
       });


       return interfaz.cast(newProxyInstance(interfaz.getClassLoader(),
               new Class<?>[]{interfaz}, new InvocationHandler() {
                   public Object invoke(final Object proxy,
                           final Method method, final Object[] args)
                           throws Throwable {
                       queue.offer(new Frame(method, args));

                       return null;
                   }
               }));
   }

   public class Frame {
       final Method method;
       final Object[] args;

       private Frame(final Method method, final Object[] args) {
           this.method = method;
           this.args = args;
       }

       private void apply(final T delegate) {
           try {
               method.invoke(delegate, args);
           } catch (final IllegalAccessException e) {
               throw new Error(e);
           } catch (final InvocationTargetException e) {
               throw new Error(e);
           }
       }
   }
}

In other words, turn calls against an interface spread across several threads into a sequence of single-threaded calls on a worker thread.

My motivation is isolating legacy non-thread-safe code in a threaded program without refactoring either the callers or the legacy code. I use a wrapper instead to make the many-threads to one-thread fix.

Sample use:

public class FacadeFactoryTest {
    private FacadeFactory<Bob> factory;

    @Before
    public void setUp() {
        factory = new FacadeFactory<Bob>(Bob.class,
                new ArrayBlockingQueue<FacadeFactory<Bob>.Frame>(1),
                newSingleThreadExecutor());
    }

    @Test(timeout = 100L)
    public void testFoo()
            throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);

        factory.facade(new Bob() {
            public void dooby() {
                latch.countDown();
            }
        }).dooby();

        latch.await();
    }

    public static interface Bob {
        void dooby();
    }
}

Tuesday, August 05, 2008

Java.next?

Stuart Halloway posts a clever take on a successor to Java: all of the above. This is part one of a series based on his No Fluff, Just Stuff presentation.

His post also gave me a quick look at side-by-side syntax for common features. I was surprised that out of clojure, jruby, groovy and scala, I preferred groovy.

Thursday, July 31, 2008

Progress in Functional Java

I have been happy lately to see the progress in Functional Java. A project truly arrives when it becomes the inspiration for other clever ideas. Witness Lazy Error Handling in Java, Part 1: The Thrower Functor.

Every few days comes another fun bit of functional programming creeping its way in to my workaday language, Java. Current wish list item: the fj team deploys to a public Maven repository so I can just say:

<dependency>
    <groupId>fj</groupId>
    <artifactId>functionaljava</artifactId>
    <version>2.8</version>
</dependency>

UPDATE: This just gets more interesting: Lazy Error Handling in Java, Part 2: Thrower is a Monad and Lazy Error Handling in Java, Part 3: Throwing Away Throws.

Thursday, July 10, 2008

Guice, main and startup configuration flags

Here is a small trick we use in an in-house program wired with Google Guice. The goal is to pick the wiring configuration from the command-line without too many contortions.

The idea is to use enums to represent the wiring, and using the command-line to pick the enum. Thus:

enum WhichOne {
   /** Uses module "A", defined elsewhere. */
   ONE(new ModuleA()),
   /** Uses module "A" and "B", defined elsewhere. */
   TWO(new ModuleA(), new ModuleB());

   private final Module module;

   WhichOne(final Module... modules) {
       module = new CompoundModule(modules);
   }

   public Module getModule() {
       return module;
   }
}

class CompoundModule extends AbstractModule {
   private final Module[] modules;

   CompoundModule(final Module... modules) {
       this.modules = modules;
   }

   @Override
   public void configure() {
       for (final Module module : modules)
           install(module);
   }
}

class Main {
    public static void main(final String... arguments) {
        // Real programs use args4j
        final WhichOne whichOne = WhichOne.valueOf(arguments[0]);
        final Module module = whichOne.getModule();
        final Injector injector = Guice.createInjector(module);

        injector.createInstance(MyProgram.class);
   }
}

Now I can pick configuration on the command line:

$ my_program ONE # use module "A"
$ my_program TWO # use module "A" and "B"

Friday, June 20, 2008

Guice support in IntelliJ IDEA

I just had a surprise reply from Dmitriy Demerov of JetBrains:

The latest Early Access Preview builds of Diana (available at http://www.jetbrains.net/confluence/display/IDEADEV/Diana+EAP ) include a plugin for Guice support. You're very much welcome to give it a try and submit your feedback on it.

I had responded to a sales manager at JetBrains that one item on my wish list for IDEA was direct Guice support.

Yippee!

Thursday, May 08, 2008

Bad concurrency advice: interned Strings

I just read Thread Signaling from Jacob Jenkov. It is fine as far as it goes to introduce the reader to Object.wait() and Object.notify().

But it has one fatal flaw: it uses a literal java.lang.String for coordinating between threads. Why is this wrong?

Strings are interned by the compiler. To quote the javadocs: All literal strings and string-valued constant expressions are interned. Using a literal string means that any other code anywhere in the JVM, even in other libraries, which use the same String literal value all share the same object for wait() and notify(). This code:

public void dastardly() {
    "".notify();  
}

will wake up a thread waiting on empty string, including one in utterly unrelated code.

Don't do that. Instead, create a fresh Object for coordinating threads. This age-worn advice for lock objects (synchronize(lock)) applies just as much to objects used to coordinate threads.

Wednesday, May 07, 2008

Friday, May 02, 2008

Good News - JavaOne 2008

JPMorgan is sending me to JavaOne 2008!

Sorry for no posts since November — work has been inordinately busy. I will post from San Francisco.

Thursday, November 22, 2007

Followup to Feature request for JDK7: delegation

A followup to Feature request for JDK7: delegation.

In the comments to my post requesting better IOC support in JDK7 Sam asks, "The keyword *is* needed... what if the delegate is editing the behaviour of one of the methods? Perhaps to do some logging. You can't do that with the original code." For some context, he refers to code like this:

class Scout implements Camper {
    public void camp() { ... }
}

class BoyScout implements Camper {
    BoyScout(Scout scout) {
        this = scout;
    }

    public void camp() {
        callHomeFirst();
        ??? // How to forward to delegate?
    }
}

I've thought about this for a bit and I think I would go with this:

public void camp() {
    callHomeFirst();
    Camper.this.camp();
}

Why?

I have several reasons:

  1. It introduces no new syntax or keywords.
  2. It does not collide with any existing use.
  3. It is reminiscent of inner class access to their outer containing class this.

My first impulse was for some kind of casting:

((Camper) this).camp();

But this is just ugly! Then using the JLS calls qualified this occurred to me, this:

Camper.this.camp();

Wednesday, October 31, 2007

Immutable objects in Java

I just read a clever post from JP Moresmau on a functional language he is writing which translates to Java.

One idea which lept out at me was how to provide setters to immutable objects in Java: the setters are instance factory methods, thus:

class DontTreadOnMe {
    public final String species;
    public final int length;

    DontTreadOnMe(String species, int length) {
        this.species = species;
        this.length = length;
    }

    // Snakes can grow but cannot change species
    DontTreadOnMe setLength(int length) {
        return new DontTreadOnMe(length);
    }
}

This works rather nicely for code which uses the convention. Unfortunately, the getter/setter idea is so firmly embedded in the fingertips of Java coders, that I expect this bug frequently:

final DontTreadOnMe copperhead
        = new DontTreadOnMe("Copperhead", 1);
// Grow in length
copperhead.setLength(2);
// Oops! Does not work as expected but compiles

My preference is for the bean properties proposal. Make immutables with read-only properties; use copy-construction to make new objects with different field values (fortunately Java copy construction is vastly simpler than C++).

Saturday, October 27, 2007

Hamcrest matchers

I missed this post from Joe Walnes a while ago on using Hamcrest matchers for more than testing.

I appreciate their DSL-like quality and clever mixture of literate class names, static factory methods and Java generics.

In his post Joe Walnes references HÃ¥kan RÃ¥berg's nice idea for filtering collections with Hamcrest matchers, but unfortunately that post links to no code, usage examples. select and reject are trivial to code:

public static <T> List<T> select(
        final Collection<T> c,
        final Matcher<T> matcher) {
    final List<T> select = new ArrayList<T>();

    for (final T t : c)
        if (matcher.matches(t))
            select.add(t);

    return select;
}

public static <T> List<T> reject(
        final Collection<T> c,
        final Matcher<T> matcher) {
    return select(c, not(matcher));
}

The statically-typed query API is not so trivial to toss off early in the morning. Hopefully HÃ¥kan RÃ¥berg will release code at some point.

UPDATE: Nat Pryce was kind enough to point to Hamcrest Collections, itself inspired by HÃ¥kan RÃ¥berg's post. Thanks, Nat!

Tuesday, October 23, 2007

Feature request for JDK7: delegation

Some while back I wrote about delegation for Java. Delegation? By this I mean direct language support for constructor-based dependency injection of interface implementation, a.k.a. mixins.

Many interesting proposals for JDK7 are in the air: the smell of change is replacing the mustiness of an aging language and I want my chance to improve Java while there is a open window of opportunity.

About delegation

For more details follow my three-year old posting. In a nutshell, delegation is assignment to this in a constructor to inject an interface implementation without the need for manually coding boilerplate forwarding methods.

An example makes this more clear:

interface Blogger {
    boolean post(final String entry);
}

// Without delegation
class MessyCoder implements Blogger {
    private final Blogger bloggerDelegate;

    MessageCodeBlogger(Blogger bloggerDelegate) {
        this.bloggerDelegate = bloggerDelegate;
    }

    public boolean post(final String entry) {
        return bloggerDelegate.post(entry);
    }
}

// With delegation
class CleanCoder implements Blogger {
    CleanCoder(Blogger bloggerDelegate) {
        this = bloggerDelegate;
    }
}

In an example this small, the gain in clarity and bug-avoidance is limited, but for larger interfaces or for multiple interfaces, the gain is proportionately larger.

The bigger picture

Providing cleaner code is only a small benefit of delegates. A larger benefit is that of mixins: dynamic implementation inheritance without breaking the single-inheritance contract of Java. Extension by composition—rather than inheritance—becomes a first-class syntax citizen of the language.

Delegates solve the mixin problem raised by Bruce Eckels about Java generics, and do so without needing aspects. (Although, behind the scenes, the compiler very well may use aspects to implement delegates. But you the over-committed programmer need not spend your short time on this point.)

Of course, you could always just fake it or do it the hard way.

UPDATE: More thoughts here and another solution.