Messaging makes its move, Part 1

Learn how to build your own Java-based messaging service

1 2 Page 2
Page 2 of 2

The following code implements a simple topic:

public interface HTopic extends Remote { // A topic provides two methods. One for subscribing to the // topic and one for publishing messages to the topic. I // haven't provided any provision for durable topic // subscribers.

public void setMessageListener(MessageListener messagelistener) throws RemoteException;

public void publish(Message message) throws RemoteException; }

public class HHTopic extends UnicastRemoteObject implements HTopic { // Subscribers are held in a simple linked-list data structure.

private LinkedList _linkedlistSubscribers = new LinkedList();

// Subscribe to this topic. This is accomplished by registering // a message listener.

public void setMessageListener(MessageListener messagelistener) throws RemoteException { synchronized (_linkedlistSubscribers) { _linkedlistSubscribers.add(messagelistener); } }

// Deliver a message to all of the subscribers subscribed to a this // topic.

public void publish(Message message) throws RemoteException { synchronized (_linkedlistSubscribers) { Enumeration enumeration = _linkedlistSubscribers.elements();

while (enumeration.hasMoreElements()) { MessageListener messagelistener = (MessageListener)enumeration.nextElement();

messagelistener.onMessage(message); } } }

// Start a topic and register it with the RMI registry.

public static void main(String [] rgstring) { try { Naming.rebind(rgstring[0], new HHTopic()); } catch (Exception exception) { System.out.println(exception); } } }

If you'd like, you can download either a zip file or a gzipped tar file containing the source files, the compiled class files, and several utilities for manipulating queues and topics.


From these three classes (and a couple of helpers such as a linked list) you can build a basic messaging service. In fact, as they are, these classes actually a provide a functional message service, but one that isn't compliant with the JMS API specification. Next month, I'll bring them into compliance by adding the required JMS veneer. See you then.

Todd Sundsted has been working with computers since computers became available in convenient desktop models. Though originally interested in building distributed object applications in C++, Todd moved on to the Java programming language when it became the obvious choice for that sort of thing. In addition to writing, Todd is President of Etcee which offers training, mentoring, consulting, and software development services.

Learn more about this topic

  • Java Message Service home page
  • JMS Specification
  • Michael Shoffner's article on message-oriented middleware (MOMs)
  • Read Todd's previous How-To Java columns
1 2 Page 2
Page 2 of 2