Thursday, October 25, 2012

Tuesday, October 23, 2012

The sensible man

Jon Pither is the sensible man. He writes a practical argument for Clojure over Java. Which is more industrial, Scala or Clojure? Yes.

Thursday, October 18, 2012

Unsafe magic heap

A brilliant post from Martin Thompson, Compact Off-Heap Structures/Tuples In Java, using sun.misc.Unsafe to avoid VM-managed heap and bypass JVM memory limits. Not of the feint of heart.

UPDATE: A lot of interesting things in Thompson's comments.

Monday, October 15, 2012

JSR-255 (JMX2) and Guice

On a new project with Guice, then, how do I magically wire my managed objects to JMX? Sadly JSR-255, aka JMX2, did not make JDK6 or JDK7 (there's always JDK8). I live in the here and now, and relied before on Spring JMX annotations and MBeanExporter.

There's no full implementation of JMX2, but covering a good minimal feature set is pojo-mbean. How to get Guice to register @MBean-annotated objects? Use injectors:

class SomeModule extends AbstractModule {
    @Override
    protected void configure() {
        bindListener(Matchers.any(), new JMXTypeListener());
    }
}

class JMXTypeListener implements TypeListener {
    @Override
    public <I> void hear(TypeLiteral<I> type,
            TypeEncounter<I> encounter) {
        Class<? super I> rawType = type.getRawType();
        // From pojo-mbean; eventually JSR-255
        if (rawType.isAnnotationPresent(MBean.class))
            encounter.register(new InjectionListener<I>() {
                @Override
                public void afterInjection(final I injectee) {
                    try {
                        // From pojo-mbean; eventually JSR-255
                        new MBeanRegistration(injectee,
                                objectName(rawType)).
                            register();
                    } catch (Exception e) {
                        encounter.addError(e);
                    }
                }
            });
    }

    private static <I> ObjectName objectName(Class<? super I> type)
            throws MalformedObjectNameException {
        return new ObjectName(type.getPackage().getName(), "type",
                type.getSimpleName());
    }
}

HTML5 Tips

I rarely have use for these things, but this one is highly practical: 8 Superlative Practices for Efficient HTML5 coding.

Thursday, September 06, 2012

The awesomeness of Uncle Bob

Uncle Bob pens The New CTO. A lunchtime conversation opens:

“So, what did you think of that?” I asked as we sat down at our regular table in the cafeteria. As I scanned the other tables in the lunchroom I could see that many other teams were leaning in to their conversation and speaking in semi-hushed tones. The normally light-hearted lunchtime banter had been replaced with a new intensity.

“It started pretty well.” said Jasper. “I mean he was nice enough at first, introducing himself as the new CTO and all.”

“Yeah, but then it started to get weird.” said Jasmine. “I mean, how dare he imply that we’re not behaving professionally? We’ve been working our asses off!”

I won't spoil the ending.

Sunday, August 12, 2012

Wednesday, August 01, 2012

Typing more to type less

My code is littered with bits like this:

import com.google.common.collect.UnmodifiableIterator;

public final class TimesIterable
        implements Iterable<Integer> {
    private final int n;

    public static Iterable<Integer> upTo(final int n) {
        return new TimesIterable(n);
    }

    public TimesIterable(final int n) {
        this.n = n;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new UnmodifiableIterator<Integer>() {
            private int i = 0;

            @Override
            public boolean hasNext() {
                return i < n;
            }

            @Override
            public Integer next() {
                return ++i;
            }
        };
    }
}

All so I can write:

import static TimesIterable.upto;
import static java.lang.System.out;

public static void main(final String... args) {
    for (int n : upTo(4))
        out.println(n);
}

To my surprise Google is not quite there yet. (I'd prefer to be wrong).

Zing zings

Azul's Zing remains amazing technology:

Where a typical JVM may spend time battling with garbage collection, McCandless says an in-memory test with the full Wikipedia English-language site loaded worked with no garbage collection pauses under Zing JVM, even with a 140GB heap.

Now free for open source.

Thursday, July 12, 2012

ESR the wit

I forgot what a wit Eric Raymond can be:


Conway’s law
is a well-known fact of life in technology organizations. Eric S. Raymond noted that “[i]f you have four groups working on a compiler, you’ll get a 4-pass compiler”.

From Conway's original:

[O]rganizations [...] are constrained to produce designs which are copies of the communication structures of these organizations.

Tuesday, July 10, 2012

Scrum is ...

Scrum is ... complex and completely over the top. That is if it isn't rescued from itself.

I still prefer XP to everything else, that may be the bias of familiarity. Scrum, and anything else agile, still beats the alternatives. To reiterate:

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

Wednesday, June 27, 2012

A string of pearls

Stuart Archibald at OpenGamma has published a series of tour de force posts. The lastest is Accessing Native Maths Libraries. FORTRAN, gcc, code generation, dynamic linking, magic code glue. What's not to love?

Tuesday, June 19, 2012

Time lies when you're calling functions

Noah Sussman notes Falsehoods programmers believe about time. My favorite:

  1. You can't be serious.

Nearly as good:

That thing about a minute being longer than an hour was a joke, right?

No.

Generating random Java strings

I found lots of misfitting advice searching Google for how to generate random strings in Java. The misfits assumed I was generating unique keys, often for web page cookies.

What I searched for was random Java strings along the lines of new Random().nextInt(), to use for probabilistic testing, but I failed to find this so I rolled my own.

Not a thing of beauty, but accomplished by goal. Hopefully someone might find this useful:

String randomString(final Random random,
        final int minLength, final int maxLength) {
    final int length = random.nextInt(maxLength - minLength) + minLength;
    final char[] chars = new char[length];
    for (int i = 0, x = chars.length; i < x; )
        do {
            final int cp = random.nextInt(0x10FFFF + 1);
            if (!Character.isDefined(cp))
                continue;
            final char[] chs = Character.toChars(cp);
            if (chs.length > x - i)
                continue;
            for (final char ch : chs)
                chars[i++] = ch;
            break;
        } while (true);

    return new String(chars);
}

To examine what you get back, consider Character.UnicodeBlock.of(int codePoint).

Monday, June 18, 2012

New in Guava 12: TypeToken, a better Class or TypeLiteral

I'm slow to read up on the Guava 12 release — it came out in April.

Among the changes is this gem: TypeToken.

Guava provides TypeToken, which uses reflection-based tricks to allow you to manipulate and query generic types, even at runtime. Think of a TypeToken as a way of creating, manipulating, and querying Type (and, implicitly Class) objects in a way that respects generics.

Note to Guice users: TypeToken is similar to Guice's TypeLiteral class, but with one important difference: it supports non-reified types such as T, List<T> or even List<? extends Number>; while TypeLiteral does not. TypeToken is also serializable and offers numerous additional utility methods.

I look forward to giving this a spin next time the need arises.

Wednesday, June 13, 2012

Emacs, your makefile friend

After long hiatus I find myself against writing (editing) makefiles. Using Emacs compile command makes all the difference. Emacs runs make in another process, sending output to an independent buffer (window, tab, panel) default named *compilation*.

In the *compilation* buffer, Emacs colorizes make's output. This greatly aids comprehension. As icing, Emacs recognizes output patterns from dozens of popular tools, and highlights them as information, warning or error as appropriate.

Emacs simplifies navigation with hyperlinking. The TAB key in *compilation* steps through warnings and errors. Magic.

As a bonus, I looked up common patterns stored in the Emacs variable, compilation-error-regexp-alist. The info page for this variable includes a link to "compilation.txt", a complete list of sample output for each supported tool. It was trivial for me to find right at the top:

* GNU style

symbol: gnu

foo.c:8: message
../foo.c:8: W: message
/tmp/foo.c:8: warning: message

That last line was my ticket. I arrange to echo similar text when something needs attention in my shell command, but without failing the entire build. I take care to break the output into separate shell echo commands so Emacs does not match prematurely when make displays executed commands. I could have prefixed my shell line with "@" (ampersand) to suppress make from printing it, but coding standards here discourage that.

a-file:
        if $(some_bad_condition_set_in_makefile) ; then \
        echo -n $@ ; \
        echo :1: warning: $@ is foobar. >&2 ; fi

I emulate the output of one of the tools Emacs groks, and I get the same magical colorizing and hyperlinking with my output:

making in /some/path
if true ; then \
 echo -n a-file ; \
 echo :1: Warning: a-file is foobar. >&2 ; fi
a-file:1: warning: a-file is foobar.

In *compilation* the TAB key jumps me to the start of a-file when it exists.

Tuesday, June 12, 2012

The generic getter idiom in Java

In our code base we represent Google protobuf messages as rooted trees, informally just trees. Nodes are necessarily heterogeneous: some are value nodes—strings, numbers, etc.—, some are roots of more trees, that is, node collections.

I recently replaced code like this:

StringNode childA = (StringNode) parent.get("child A's name");
Int32Node childB = (Int32Node) parent.get("child B's name");

With code like this:

StringNode childA = parent.get("child A's name");
Int32Node childB = parent.get("child B's name");

How did I do this? I changed the definition of "get" from:

public Node get(final String name) {
    // Clever implementation
}

To:

public <N extends Node> N get(final String name) {
    // Same implementation with some "(N)" casts
}

When the compiler can infer the return type of "get", it will, saving you writing now and reading later. In those cases where it cannot infer the type, you still help:

final String valueA = (String) ((StringNode) parent).get("child A's name").getValue();
final Integer valueB = (Integer) ((Int32Node) parent).get("child B's name").getValue();

Becomes:

final String valueA = parent.<StringNode>get("child A's name").getValue();
final Integer valueB = parent.<Int32Node>get("child B's name").getValue();

There is still a type cast, but you spell it differently using the generics system. Note "getValue" uses the same idiom as "get"; the return type can be inferred, no extra writing needed.

I'm going to call this pattern the Generic Getter Idiom until I find a good reference.

Related: Crossing generics and covariant returns

Thursday, June 07, 2012

The view of things to come Java

Lukas Eder notes the possibility of collection and structural literals in Java. A man can dream, can't he? Happily, this dream is built on more than wisps of fancy, just. I don't hold my breath.

Friday, June 01, 2012

Thursday, May 24, 2012

Picture GCC mangling

Matt Godbolt posts GCC Explorer - an interactive take on compilation.

One of the things I spend a fair amount of time doing at work is compiling my C/C++ code and looking at the disassembly output. Call me old-fashioned, but I think sometimes the only way to really grok your code is to see what the processor will actually execute. Particularly with some of the newer features of C++11 — lambdas, move constructors, threading primitives etc — it’s nice to be able to see how your elegant code becomes beautiful (and maybe even fairly optimal) machine code.

I’d managed to get my pipeline for taking small snippets of C code, building them with GCC, de-mangling the output, musing on the assembly, tweaking the input and then repeating over and over again.

See github for sources.

Wednesday, May 16, 2012

Uncle Bob on No DB

Another beautiful rant from Uncle Bob:

Here’s what an application should look like. The use cases should be the highest level and most visible architectural entities. The use cases are at the center. Always! Databases and frameworks are details! You don’t have to decide upon them up front. You can push them off until later, once you’ve got all the use cases and business rules figured out, written, and tested.

8th light must be something else.

Wednesday, May 09, 2012

Is Continuous Delivery agile?

Keif Morris thoughtfully compares/contrasts Agile to Continuous Delivery (CD).

Of course the answer to the question posed in the post title is Yes, Continuous Delivery is agile. Very agile, in fact.

Keif raises several concerns traditional Agile has with Continuous Delivery. I admit to being from the old school, XP, and am a little nervous around CD. But I embrace its spirit.

With Agile leaving small release messes to clean up each iteration, or for Waterfall one giant mess to clean up in the release phase, is bad for the nerves too. At least CD picks up after itself in an ongoing basis.

As a daily Java programmer Maven makes a hash of this as Keif points out. But as with many things related to Maven, you gain a few pains and lose several others for net betterment. How does CD treat the snapshot ailment?