This example shows how JBoss Messaging would avoid running out of resources by paging messages.
A maxSize could be specified per Destination on the destinations settings, or a globalMaxSize could also be set on the maing config file.
When the buffered messages are consuming too much memory, JBossMessaging starts writing messages on the file-system, and as the memory is released by message acknowledgement or transaction commits those messages are recovered from disk and placed in memory
Acknowledgement plays an important factor on paging as messages will stay on the file system until the memory is released
A Queue is used to send messages point to point, from a producer to a consumer. The queue guarantees message ordering between these 2 points.
To run the example, simply type ant
from this directory
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext();
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
Queue pageQueue = (Queue) initialContext.lookup("/queue/pagingQueue");
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
connection = cf.createConnection();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer pageMessageProducer = session.createProducer(pageQueue);
pageMessageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
BytesMessage message = session.createBytesMessage();
message.writeBytes(new byte[10 * 1024]);
for (int i = 0; i < 20; i++)
{
pageMessageProducer.send(message);
}
MessageProducer messageProducer = session.createProducer(queue);
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
for (int i = 0; i < 30000; i++)
{
messageProducer.send(message);
}
// Thread.sleep(30000); // if you want to just our of curiosity, you can sleep here and inspect the created files just for
MessageConsumer messageConsumer = session.createConsumer(queue);
connection.start();
for (int i = 0; i < 30000; i++)
{
message = (BytesMessage)messageConsumer.receive(1000);
if (i % 1000 == 0)
{
System.out.println("Received " + i + " messages");
message.acknowledge();
}
}
messageConsumer.close();
messageConsumer = session.createConsumer(pageQueue);
for (int i = 0; i < 20; i++)
{
message = (BytesMessage)messageConsumer.receive(1000);
System.out.println("Received message " + i + " from pageQueue");
message.acknowledge();
}
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}