0

我了解如果计时器遇到异常,它将停止运行。但这是我的代码:

@Startup
@Singleton
public class TimerBean
{
    private HashMap myMap;    

    @EJB
    private MyBean myBean;

    @Schedule (minute="*/1" ....)
    public void myTimer()
    {  
       myMap.clear();
       myMap = myBean.createData(); //this takes a few seconds to finish

    }
...
}

因此计时器每 1 分钟触发一次,并调用 myBean 从数据库中获取数据并填充哈希图。

现在在另一个类中,客户端调用 restFul Web 服务来获取哈希图,代码如下:

@EJB
private TimerBean timerBean;

@GET
@Path("query")
@Produces(MediaType.APPLICATION_JSON)
public MyObject getData()
{
    timerBean.getMyMap(); //call timerBean to get the hashmap
    //in case the hashmap returned is empty, meaning it's not ready yet
     //(it's still in the process of populating)
     //throw an WebApplicationException 
    //so that from the user's end, I can show a different web page
    //and ask the user to wait.

}

发生的情况是,有时,当它抛出异常时,它也会导致计时器再次停止工作。为什么?计时器 itelt 没有遇到任何异常。

我意识到潜在的问题是当用户尝试获取哈希图时,计时器可能正在填充哈希图。我应该怎么做才能防止这种情况发生?就像阻止 Web 服务调用直到它准备好?

谢谢

4

1 回答 1

0

我不明白为什么计时器会停止,但是您可以这样做以防止在填充地图之前调用该方法:

@PostConstruct
public void atStartup() {
  myMap = myBean.createData(); 
}

@Startup保证此方法将在调用任何其他方法之前执行。

于 2012-09-20T21:54:54.703 回答