Example: Creating Callable and Runnable tasks
You can create a task that dynamically subscribes to a topic and any component can add a message listener on demand.
The following is an example of a task that dynamically subscribes to a
topic:
class SampleTask implements Callable<Object>
{
Set<MessageListener> listeners =
Collections.newSetFromMap(new ConcurrentHashMap<MessageListener, Boolean>);
Topic targetTopic;
TopicConnectionFactory tcf;
public SampleTask(TopicConnectionFactory tcf, Topic targetTopic)
{
this.targetTopic = targetTopic;
this.tcf = tcf;
}
public void addMessageListener(MessageListener listener)
{
listeners.add(listener);
}
public Object call() throws JMSException
{
// Set up JMS.
TopicConnection tc = tcf.createConnection();
try
{
TopicSession sess = tc.createSession(false, Session.AUTOACK);
tc.start();
while( !Thread.currentThread().isInterrupted() )
{
// Block for up to 5 seconds.
Message msg = sess.receiveMessage(5000);
if(msg != null)
{
for (MessageListener listener : listeners)
// Fire an event when we get a message.
listener.onMessage(msg);
}
}
tc.close();
}
finally
{
if (tc != null) tc.close();
}
return null;
}
}
As a result, any component can add a message listener on demand, which enables components to subscribe to a topic in a more scalable way than by simply giving each client subscriber its own thread.