The SimpleQueue
by Oliver on Apr.26, 2009, under geeking out
Following on from the design issues in XMediaStream, the plan of implementing a queue to hold the SimpleMessageObjects received over multicast has been implemented.
This was done with three new classes, and a modification to MulticastShoutcastServer.java.
SimpleQueue.java
This class holds the queue implementation. In a bid for code re-use, the underlying data structure is a simple array of Objects. A read pointer and write pointer point to the next read and write position (wrapping back to zero when they reach array.length). When an object is read, that position in the array is set to null. Therefore whenever a write is taking place, the position in the array is checked to make sure it is null. If it isn’t null, the write pointer has caught up to the read pointer and we’re about to overwrite an object that hasn’t yet been read. If this happens, the queue will re-size and copy the unread objects into the new queue, setting the read and write pointers appropriately.
MulticastPacketListener.java
This is pretty simple, it continuously listens for new multicast packets and for each one receives, check’s it’s for this configured source and if so, add it to the SimpleQueue.
QueueShoutcastServerStreamer.java
This continuously reads from the queue and sends the mp3 bytes to the listening squeezebox.
The only problem encountered was if the squeezebox disconnected (or was started and stopped). Both MulticastPacketListener’s and QueueShoutcastServerStreamer’s are Threads, so if the squeezebox disconnected, the QueueShoutcastServerStreamer stopped reading from the queue but the MulticastPacketListener kept writing new packets to the queue. The queue therefore continuously re-sized until the JVM ran out of memory.
To get round this problem, the SimpleQueue keeps a timestamp every time an object is added to or read from the queue. The MulticastPacketListener then checks each time it writes a new object when the last read took place, if it was more than 30s ago, it deems the reading client is dead and ends.
This implementation has been running successfully for a couple of days now with no glitches in the music, no dropped multicast packets and only a few queue resizes.