Thursday, December 13, 2012

Passing of an era: No more i386

Thus spake Linus Torvalds:

Pull "Nuke 386-DX/SX support" from Ingo Molnar:
 "This tree removes ancient-386-CPUs support and thus zaps quite a bit
  of complexity:

    24 files changed, 56 insertions(+), 425 deletions(-)

  ... which complexity has plagued us with extra work whenever we wanted
  to change SMP primitives, for years.

  Unfortunately there's a nostalgic cost: your old original 386 DX33
  system from early 1991 won't be able to boot modern Linux kernels
  anymore.  Sniff."

I'm not sentimental.  Good riddance.

Tuesday, December 04, 2012

Guicing your jars, part 2

In Guicing your jars I mention using Java's service loader feature to automate finding modules for Guice, along these lines:

public class MetaInfServicesModule
        extends AbstractModule {
    @Override
    protected void configure() {
        for (final Module module : ServiceLoader.load(Module.class))
            install(module);
    }
}

What I did not mention was the secret sauce, Kohsuke's MetaInfServices annotation processor which creates the META-INF/services file for you:

@MetaInfServices(Module.class)
public class FooModule
        extends AbstractModule {
    @Override
    protected void configure() {
        // Awesome foo-ness here
    }
}

Now using your Maven runtime dependencies to control the classpath, Guice automatically installs your modules:

Guice.createInjector(new MetaInfServicesModule());

(Dependencies between modules is beyond the scope of this post!)

Coming in Kernel 3.7 from The H-Open

  1. Filesystems & storage
  2. Networking
  3. Infrastructure
  4. Drivers
  5. CPU and platform code

Friday, November 30, 2012

WebPageTest

Ryan Hurst posts How Facebook can avoid losing $100M in revenue when they switch to always-on SSL, an interesting discussion of web page performance when using SSL.

What I noticed: WebPageTest, a fantastic resource for tuning public web pages courtesy AOL, Google & others. WebPageTest can also be downloaded, for testing your internal web site.

Sunday, November 25, 2012

Monday, November 19, 2012

Alternative to Java 8 virtual extension methods

Tired of waiting for Java 8? Project Lombok brings a little piece to you today, virtual extension methods similar to those proposed for JDK8. The most interesting bit: Lombok works using only JDK annotation processors and no required run-time library.

JUnit testing that a call blocks

Certain that I missed an existing solution, I post this in hopes of helping anyone who also misses it. But if you know a better way, please comment.

Usage

class SomeTest {
    @Test(timeout = 1000L)
    public void shouldBlock() {
        assertBlocks(new BlockingCall() {
            @Override
            public void call()
                    throws InterruptedException {
                // My blocking code here
            }
        });
    }
}

Implementation

import javax.annotation.Nonnull;
import java.util.Timer;
import java.util.TimerTask;

import static java.lang.String.format;
import static java.lang.Thread.currentThread;
import static org.junit.Assert.fail;

/**
 * {@code BlockingCall} supports blocking call assertion for JUnit tests.
 *
 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
 */
public interface BlockingCall {
    /**
     * Calls blocking code.  The blocking code must throw {@code
     * InterruptedException} when its current thread is interrupted.
     *
     * @throws InterruptedException if interrupted.
     */
    void call()
            throws InterruptedException;

    /** Wrapper class for block assertion. */
    public static final class Assert {
        /**
         * Asserts the given <var>code</var> blocks at least 100ms.  Interrupts
         * the blocking code after 100ms and checks {@code InterruptedException}
         * was thrown.  When not blocking, appends <var>block</var> to the
         * failure message.
         *
         * @param block the blocking call, never missing
         */
        public static void assertBlocks(@Nonnull final BlockingCall block) {
            final Timer timer = new Timer(true);
            try {
                final Thread current = currentThread();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        current.interrupt();
                    }
                }, 100L);
                block.call();
                fail(format("Did not block: %s", block));
            } catch (final InterruptedException ignored) {
            } finally {
                timer.cancel();
            }
        }
    }
}

UPDATE: Idioms like this would be far more attractive with Java 8 lambdas:

public void shouldBlock() {
    assertBlocks(() -> { /* blocking code */ });
}

Friday, November 09, 2012

Python's enumerate for Java

Surprisingly I did not find Python's enumerate in Guava Iterables.

A little static import and all is well:

import com.google.common.collect.UnmodifiableIterator;

import javax.annotation.Nonnull;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * {@code EnumerateIterable} wraps an iterable like Python {@code enumerate}.
 *
 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
 */
public final class EnumerateIterable<T>
        implements Iterable<Entry<Integer, T>> {
    @Nonnull
    private final Iterable<T> delegate;

    public EnumerateIterable(@Nonnull final Iterable<T> delegate) {
        this.delegate = delegate;
    }

    /**
     * Creates a new enumerated iterable for the given <var>delegate</var>.
     *
     * @param delegate the underlying iterable, never missing
     * @param <T> the underlying wrapped type
     *
     * @return the new enumerated iterable, never missing
     */
    @Nonnull
    public static <T> Iterable<Entry<Integer, T>> enumerate(@Nonnull final Iterable<T> delegate) {
        return new EnumerateIterable<>(delegate);
    }

    @Nonnull
    @Override
    public Iterator<Entry<Integer, T>> iterator() {
        return new EnumerateIterator<>(delegate);
    }

    private static final class EnumerateIterator<T>
            extends UnmodifiableIterator<Entry<Integer, T>> {
        @Nonnull
        private final Iterator<T> it;
        int i;

        EnumerateIterator(@Nonnull final Iterable<T> delegate) {
            it = delegate.iterator();
            i = 0;
        }

        @Override
        public boolean hasNext() {
            return it.hasNext();
        }

        @Override
        @Nonnull
        public Entry<Integer, T> next() {
            return new SimpleImmutableEntry<>(i++, it.next());
        }
    }
}

UPDATE: Completeness requires a static factory method for arrays as well as iterables.

ISO8601 UTC with XStream

I need ISO8601 conversion with XStream for UTC (GMT/Zulu) time. Originally I went with ISO8601DateConverter which comes with XStream and uses Joda. However I found that it read in UTC (GMT/Zulu) time but wrote back out local time.

To fix this I wrote my own converter using JAXB in the JDK, and dropped the Joda runtime dependency from my project.

I unit tested full roundtrip with "2012-10-22T12:34:56Z". The original converter parsed correctly but serialized as "2012-10-22T07:34:56-05:00". My converter serializes as the input string.

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

import java.util.Date;
import java.util.GregorianCalendar;

import static java.util.TimeZone.getTimeZone;
import static javax.xml.bind.DatatypeConverter.parseDateTime;
import static javax.xml.bind.DatatypeConverter.printDateTime;

/**
 * {@code UTCConverter} converts {@code java.util.Date} objects in ISO8601
 * format for UTC without milliseconds.
 *
 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
 */
public final class UTCConverter
        extends AbstractSingleValueConverter {
    @Override
    public boolean canConvert(final Class type) {
        return Date.class.isAssignableFrom(type);
    }

    @Override
    public String toString(final Object obj) {
        final GregorianCalendar gmt = new GregorianCalendar(getTimeZone("GMT"));
        gmt.setTime(Date.class.cast(obj));
        return printDateTime(gmt);
    }

    @Override
    public Object fromString(final String str) {
        return parseDateTime(str).getTime();
    }
}

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