Instance Selection Algorithm: spymemcached vs. memcached-session-manager

I recently evaluated whether to use memcached-session-manager [1] for one of our webapps. Although memcached-session-manager bases on spymemcached [2] for communicating with memcached, I was surprised that it uses a significant different algorithm for selecting a memcached instance (out of a pool of given memcached instances) than the native implementation of spymemcached.


Spymemcached selects the instance by calculating a hash of the element’s key and using that hash to determine the instance. Simplified this could be done by compute:

server = serverlist[hash(key)%serverlist.length]

To distribute the elements uniformly on all nodes often Consistent Hashing [3], e.g. KETAMA, is used as hash function. See [4] for details.


In contrast to that, memcached-session-manager doesn’t use hashing at all – it simply “selects the memcached node randomly” [5] (excluding failover nodes). After that the node id is encoded in the session id like 72d9ffcb00d836b3248d8bd95ce2e641-n1.tomcat1 (“n1”). All further accesses are selected by this value.

How to not convert a Boolean to boolean

On my last code review session I stumbled over that lovely piece of code:

Boolean wrapper = foo();
boolean primitive = Boolean.parseBoolean(""+wrapper);

A somehow interesting way of converting a Boolean to it’s primitive.

I guess this was done to avoid a NullPointerException in case wrapper is null. But it violates one simple rule: write readable code.

Of course, this line isn’t hard to understand—but do you know for sure the outcome of the parseBoolean-method when the argument is null or an empty String? Is it ‘false’, ‘true’ or will the method throw an exception? To make it even worse: “”+wrapper will return the String “null” (yep – a String of length 4) when wrapper is null. Can parseBoolean handle this too?

So how to (really) avoid a NullPointer here? Simply use:

Boolean wrapper = foo();
boolean primitive = wrapper == null ? false : wrapper.booleanValue();

or (cooler but a little less readable):

Boolean wrapper = foo();
boolean primitive = wrapper != null && wrapper.booleanValue();