2012-09-20 38 views
0

我知道如果定时器遇到异常,它将停止运行。但这里是我的代码:从其他方法抛出异常后EJB定时器停止

@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从数据库中获取数据并填充HashMap中。

在不同的类

现在,客户端发出RESTful Web服务调用来获取HashMap中,这里的代码:

@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. 

} 

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

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

感谢

+0

http://stackoverflow.com/questions/14530717/avoid-expunging-timer-on-glassfish这可能是有用的情况下,你不能避免抛出异常 –

回答

0

我不明白为什么计时器会停止,但这里是你可以做什么防止调用此方法的地图被填充之前:

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

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