如何在activeMQ中发生事件之前暂停

时间:2013-04-14 01:29:35

标签: java events listener activemq

我希望方法等到侦听器的事件发生。我该怎么做到这一点? 在我的程序中,我想循环,直到事件的结果符合某些标准,否则,我将无休止地发送请求

public void run(double r, double sigma, double strike, double s0, String t, int d) throws JMSException, InterruptedException {
  double actureError = 0.0;
  double epsilon = 0.00001;

  // iterate until the relative error rate is less than requested (converged)
  while ((actureError < epsilon) || (actureError > ESTIMATION_ERROR)) {
    sendRequest(r, sigma, strike, s0, t, d);

    Topic topic = session.createTopic("topic");
    MessageConsumer consumer = session.createConsumer(topic); 
    OptionMessageListener listener = new OptionMessageListener(task);
    consumer.setMessageListener(listener);

    double absoluteError = y * task.getSigma()
      / Math.sqrt(task.getCount());
    actureError = absoluteError / (task.getAvg() + epsilon);
  }

  return task.getAvg() * Math.exp(-r * 252);
}

public void sendRequest(double r, double sigma, double strike, double s0, String t, int d) throws JMSException {
  // send request to the client
  MessageProducer producer = session.createProducer(queue);
  OptionRequest request = new OptionRequest(r, sigma, strike, s0, t, d, null);
  ObjectMessage requestMessage = session.createObjectMessage(request);
  producer.send(requestMessage);
}

public class OptionMessageListener implements MessageListener {
  private Task task;

  public OptionMessageListener(Task task) {
    this.task = task;
  }

  @Override
  public void onMessage(Message message) {
    if (message instanceof ObjectMessage) {
      ObjectMessage objectMessage = (ObjectMessage) message;
      try {
        Result result = (Result) objectMessage.getObject();      
        double payout = result.getPayout();
        task.addPayout(payout);
      } catch (JMSException e) {
        e.printStackTrace();
      } 
    }
  }
}

我是activeMQ的新手,任何人都可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:0)

将CountDownLatch设置为1并在主应用程序中等待它。然后,当满足条件时,您可以让onMessage方法倒数。这也允许您在等待呼叫上设置超时值,以便您的应用程序可以唤醒并检查其关闭时间或其他工作等。