if you are ok with an external dependency, vibe has a channel implementation that returns the number of messages in the buffer http://vibed.org/api/vibe.core.channel/Channel