如何在activeMq抛出异常时创建一个后台线程,它将在类级别向量上工作?

时间:2016-03-02 07:27:24

标签: java multithreading

我在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
        }
    }
}

0 个答案:

没有答案