Tuesday, March 31, 2009

Trivial for-each sugar

A snippet of for-each syntatic sugar for Java loops:

for (final Person person : each (ALICE, BOB, CAT))
    person.say("Hello!");

And elsewhere:

public static <T> T[] each(final T... array) {
    return array;
}

Wednesday, March 25, 2009

Java code beautifier

Where are the Java code beautifiers? My criteria:

  1. Formats in standard SUN Java style
  2. Works on JDK5+ Java code
  3. No licensing required—free as in beer

Not very many criteria! And yet … very little turned up that did not violate one requirement or the other. I came up with exactly one match: Jacobe, personal edition.

Wednesday, March 04, 2009

Two miracle utilities: rlwrap and screen

Two miracle utilities: rlwrap and screen.

rlwrap

Ever wish you had nice command-line editing like BASH but the tool you are using is hopeless? rlwrap is the tool for the job: it is a readline wrapper for any program that reads from stdin. A classic use case is wrapping sqlplus.

screen

Say you have an on-again, off-again shell session you come back to throughout the day. You could keep a shell window open all day. But what if you change machines, say from a laptop to a desktop and back again? screen is the tool for the job: it is a full-screen window manager for terminal sessions. Disconnect from the current session, keep screen running in the background, and reconnect later at your convience. Nothing is lost.

Tuesday, February 17, 2009

To agile, or not to agile

Two of my favorite authorities on programming disagree over agile. This is hardly surprising as they are Joel Spolsky and Robert Martin ("Uncle Bob"), both men known for their strong and well-supported opinions, and neither suffer fools gladly.

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