在向ActiveMQ发送消息的情况下删除Thread.sleep()

时间:2018-06-04 19:17:57

标签: sonarqube activemq

我在我的项目中修复了声纳lint错误。我看过一个代码块,其中声纳lint给我错误的规则squid:S2276来替换Thread.sleep(100);用wait()。但是wait()应该在条件循环中以逃避虚假的唤醒问题。但我没有得到如何使用的条件。

我可以在没有睡眠的情况下实现同样的目标吗()

public class ACTOOBEventSubSMSProducer {

private ACTOOBEventSubSMSProducer(){
    super();
}
private static Logger logger = LoggerManager.getInstance().getCoreProcessingLogger();
public static final String CONNECTION_FACTORY = "java:jboss/activemq/ConnectionFactory";
static final String QUEUE_NAME = "java:jboss/exported/jms/queue/actOOBEventSubscriptionSMS";
static ConnectionFactory connectionFactory = null;
static Connection connection = null;
static Session session = null;
static Destination destination = null;
static MessageProducer messageProducer = null;

static {
    connectionFactory = ServiceLocator.getJmsConnectionFactory(CONNECTION_FACTORY);
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
        destination = ServiceLocator.getJmsDestination(QUEUE_NAME);
        messageProducer = session.createProducer(destination);
        messageProducer.setDisableMessageID(true);
        messageProducer.setDisableMessageTimestamp(true);
    } catch (JMSException e) {
        logger.error("Error in creating ConnectionFactory",e);
    }
}

/**
 * This method sends OOB Event SMS Message in Queue.
 * 
 * @param message
 */
public static synchronized void sendMessage(Serializable payload) throws JmsProducerException {
    try {
        ObjectMessage message = session.createObjectMessage(payload);
        messageProducer.send(message, javax.jms.DeliveryMode.NON_PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY,
                1800000);
    } catch (JMSException je) {
        try {
            Thread.sleep(100);
            ObjectMessage message = session.createObjectMessage(payload);
            messageProducer.send(message, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY,
                    1800000);
        } catch (JMSException jee) {
            logger.error("Error in sendMessage()",jee);
            throw new JmsProducerException(jee);
        } catch (InterruptedException ie) {
            logger.error("Error in sendMessage()",ie);
            Thread.currentThread().interrupt();
            throw new JmsProducerException(ie);
        }
    } catch (ServiceLocatorException sle) {
        logger.error("Error in sendMessage()",sle);
        throw new JmsProducerException(sle);
    }
}

}

1 个答案:

答案 0 :(得分:0)

一个精心设计的for循环,迭代计数是你想要重试的次数,一些异常处理逻辑可以在事情有效的情况下打破循环,或者以更清晰的方式处理,否则使用ScheduledThreadPoolExecutor或者或计时器将是一个选项。