在java中设置方法的运行时间限制
我有一个返回String的方法,是否有可能在某个时间阈值后,该方法返回一些特定的字符串?
Guava库有一个非常好的TimeLimiter
,可以让你在任何由接口定义的方法上执行此操作。 它可以为您的对象生成具有“内置”超时的代理。
在使用Runtime.getRuntime().exec(command)
外部进程时,我做了类似的事情。 我想你可以在你的方法中做这样的事情:
Timer timer = new Timer(true); InterruptTimerTask interruptTimerTask = new InterruptTimerTask(Thread.currentThread()); timer.schedule(interruptTimerTask, waitTimeout); try { // put here the portion of code that may take more than "waitTimeout" } catch (InterruptedException e) { log.error("timeout exeeded); } finally { timer.cancel(); }
这是InterruptTimerTask
/* * A TimerTask that interrupts the specified thread when run. */ protected class InterruptTimerTask extends TimerTask { private Thread theTread; public InterruptTimerTask(Thread theTread) { this.theTread = theTread; } @Override public void run() { theTread.interrupt(); } }
正如@MarcoS的回答
我发现如果方法锁定某些东西而不释放CPU时间到Timer,则不会引发超时。 然后Timer无法启动新线程。 所以我立即通过启动线程改变一点并在线程内部睡眠。
InterruptTimerTaskAddDel interruptTimerTask = new InterruptTimerTaskAddDel( Thread.currentThread(),timeout_msec); timer.schedule(interruptTimerTask, 0); /* * A TimerTask that interrupts the specified thread when run. */ class InterruptTimerTaskAddDel extends TimerTask { private Thread theTread; private long timeout; public InterruptTimerTaskAddDel(Thread theTread,long i_timeout) { this.theTread = theTread; timeout=i_timeout; } @Override public void run() { try { Thread.currentThread().sleep(timeout); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(System.err); } theTread.interrupt(); } }
您可以使用来自jcabi-aspects的 AOP和@Timeable
注释(我是开发人员):
@Timeable(limit = 1, unit = TimeUnit.SECONDS) String load(String resource) { while (true) { if (Thread.currentThread.isInterrupted()) { throw new IllegalStateException("time out"); } // execution as usual } }
当达到时间限制时,您的线程将被interrupted()
标志设置为true
,您的工作是正确处理这种情况并停止执行。
此外,请查看此博客文章: http : //www.yegor256.com/2014/06/20/limit-method-execution-time.html