且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 Java Future.get(timeout) 不可靠?

更新时间:2023-02-09 22:52:10

没有理由期望测试通过.鉴于您提交任务以供执行,然后等待其完成,在您等待 Future#get() 之前可能会经过任何时间,让任务有足够的时间来耗尽睡眠持续时间并完成.

There is no reason to expect the test to pass. Given that you submit the task for execution and then wait on its completion, any amount of time could pass before your wait on Future#get() begins, allowing the task plenty of time to exhaust the sleep duration and complete.

在您的情况下,我们可以假设 Executor 中运行的线程获得焦点,而您通过 test() 运行的主线程暂停,尽管处于可运行状态.至于观察到的将提交的任务拖延两秒和三秒之间的差异,我希望您会发现甚至三秒都不够的情况,这取决于您计算机上的其他进程正在忙于做什么.

In your case, we can assume that the thread running within the Executor gets focus while your main thread running through test() is on hold, despite being in a runnable state. As for the observed difference between stalling the submitted task for two and three seconds, I expect you could find situations where even three seconds is insufficient, depending on what other processes are busy doing on your computer.