等待最多X秒的异步EJB [英] Waiting at most X seconds for Async EJBs

查看:121
本文介绍了等待最多X秒的异步EJB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端 EJB ,它调用4个异步 EJB s,应该让它们全都运行5秒钟。 5秒钟后,客户端 EJB从完成运行的 Future 对象收集就绪结果,并返回输出。

I have a "client" EJB that invokes 4 Asynchronous EJBs and should give them all 5 seconds to run. After 5 seconds the "client" EJB collects the ready results from Future object that finished running, and returns output.

客户端部分的等待有问题。我试图调用 future.get(5,TimeUnit.MILLISECONDS)
似乎有时异步 EJB s 在超时后开始运行
是否有正确的方法?

I have a problem with the "waiting" in client part. I tried to invoke future.get(5, TimeUnit.MILLISECONDS) It seems like sometimes async EJBs start to run after the timeout. Is there a correct way to do it?

1)在<$ c中收集未来个对象$ c>地图:

1) Collect Future objects in Map:

    Map<String, Future> futureMap = new HashMap<String, Future>();
    for (String userID: users) {
            Future<Set<FrontPageData>> test = util.asyncGetData(userID);
            futureMap.put(serviceID, test);

    }
    return futureMap;

2)然后我从 Future 对象

    final long now = Calendar.getInstance().getTimeInMillis();
    final long end = now + TimeUnit.SECONDS.toMillis(5)
    Map<String, Object> output = new HashMap<String, Object>();
    Object data;
    for (String userID: futureMap.keySet()) {
        Future future= futureMap.get(userID);
        try {
            //check how much time left till the end
            long timeout = end - Calendar.getInstance().getTimeInMillis();
            data = future.get(timeout, TimeUnit.MILLISECONDS);
            output.put(userID, data);
        } catch (Exception e) {//write to logs
        } 
    }
    return output;
}

谢谢

推荐答案

我不认为您的客户端应该了解详细信息,是否仍需安排异步代码还是已运行了5秒钟。

I don't think your client should be aware of the details whether the async code still has to be scheduled or whether it has been running for those 5 seconds.

您的客户应该关心的是总等待时间。由于没有系统具有无限的资源,因此不能保证异步代码立即开始运行。

All your client should be concerned about is the total waiting time. Since no system has unlimited resources, there can't be any guarantee that the async code starts running right away.

如果要将实际执行时间限制为5秒,唯一现实的方法是在执行代码的Bean中执行此操作。

If you want to limit the actual execution time to 5 seconds, the only realistic way is to do this in the bean that executes the code.

ps

不相关您的问题,但是为什么要对超时进行这种奇怪的计算呢?现在,您执行现在+ 5秒-现在,这又是5秒。

Not related to your question, but why do this weird calculation for timeout? You now do "now + 5 seconds - now", which is 5 seconds again.

并且,如果您遍历Map并需要值和键,则您可以遍历entrySet,而不是遍历键集,然后对每个键进行 get()

And, if you iterate over a Map and need both the value and key, you can iterate over the entrySet, instead of over the key set and then doing a get() for each key.

这篇关于等待最多X秒的异步EJB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆