我在activeMq中有一个主题的发布者,如果发生异常,会将TextMessage
推送到向量。我想在异常发生时生成一个线程,并且该线程应该继续重试以将消息推送到同一主题。但是在异常情况下应该只有一个线程而不是多个线程。
private Vector<TextMessage> pendingQueue = new Vector<TextMessage>();
@Override
public void sendMessage(Object myMessage)
{
try
{
factory = new ActiveMQConnectionFactory(activeMQServerURL);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic(cmdTopicName);
producer = session.createProducer(destination);
message = session.createTextMessage();
message.setText(new Gson().toJson(myMessage));
producer.send(message);
}
catch (JMSException e)
{
pendingQueue.add(message);
runBackgroundDLQJobs();
}
}
public void runBackgroundDLQJobs()
{
bgThread.start();
}
运行bgThread的方法:
@Override
public void run()
{
while (pendingQueue.size() > 0)
{
try
{
int idx = 0;
while (idx < pendingQueue.size())
{
boolean sendDLQMessagesSuccess = sendDLQMessages(pendingQueue.get(idx));
if (sendDLQMessagesSuccess)
{
pendingQueue.remove(idx);
idx++;
}
else
{
Thread.sleep(5000);
}
}
}
catch (Exception e)
{
//DoSomething
}
}
}