Friday, September 25, 2009

Keeping a current timestamp in a Java concurrent map

Tricker than I like: In Java, how do you keep a map with the values being the "most recent timestamp" for the key? How do you do this for a concurrent map with multiple threads updating?

boolean isLatest(final K key, final long newTimestamp,
        final ConcurrentMap<K, Long> map) {
    Long oldTimestamp = map.putIfAbsent(key, newTimestamp);

    // If we are first, there is no previous to compare
    // with
    if (null == oldTimestamp)
        return true;

    // Make sure we are still the most recent
    while (newTimestamp > oldTimestamp) {
        if (map.replace(key, oldTimestamp, newTimestamp))
            // No other thread has updated, we are most
            // recent
            return true;

        // Another thread got here first, recheck
        oldTimestamp = map.get(key);
    }

    // Another thread put in a newer update, we are not
    // most recent
    return false;
}

As with all multi-threaded coding, bugs are easy to make and hard to spot. If I have made one, please let me know!

UPDATE: Fixed a typo. Thanks, David!

Friday, September 11, 2009

Sunday, September 06, 2009

Fast reflection, a cool post

"Coding Masters" (sorry, I didn't find his name) posts an interesting dissection of reflection and tunes until it is as quick as normal code. This is one for my toolbox.

Thursday, September 03, 2009

More on favorite idioms

lambdaj does a much better job than I did:

List<Integer> biggerThan3 = filter(greaterThan(3), asList(1, 2, 3, 4, 5));

Qi4j 1.0-RC1

Qi4j realizes much of the promise of annotations. Mixins and aspects without code or bytecode generation, what's not to love?