{
int commitCounter = 0;
try
{
Session session = conn.createSession(true, Session.SESSION_TRANSACTED);
MessageConsumer consumer = session.createConsumer((Destination)queue);
int lastCount = messageCount;
while (true)
{
TextMessage message = (TextMessage) consumer.receive(5000);
if (message == null)
{
break;
}
log.debug("read message " + message.getText());
// alternating commits and rollbacks
if ( (commitCounter++) % 2 == 0)
{
messagesRead += (messageCount - lastCount);
lastCount = messageCount;
log.debug("commit");
session.commit();
}
else
{
lastCount = messageCount;
log.debug("rollback");
session.rollback();
}
messageCount++;
if (messageCount %7 == 0)
{
session.close();
session = conn.createSession(true, Session.SESSION_TRANSACTED);
consumer = session.createConsumer((Destination)queue);
}
if (messageCount % 50 == 0)
{
log.info("Reader " + index + " read " + messageCount + " messages");
}
}
messagesRead += (messageCount - lastCount);
session.commit();
consumer.close();
session.close();
}
catch (Exception e)
{
e.printStackTrace();