取消长时间运行的正则表达式匹配?
2022-09-02 00:31:12
假设我正在运行一个服务,用户可以提交一个正则表达式来搜索大量数据。如果用户提交的正则表达式非常慢(即 Matcher.find() 需要几分钟才能返回),我想要一种方法来取消该匹配。我能想到这样做的唯一方法是让另一个线程监视匹配需要多长时间,并在必要时使用Thread.stop()取消它。
成员变量:
long REGEX_TIMEOUT = 30000L;
Object lock = new Object();
boolean finished = false;
Thread matcherThread;
匹配器线程:
try {
matcherThread = Thread.currentThread();
// imagine code to start monitor thread is here
try {
matched = matcher.find();
} finally {
synchronized (lock) {
finished = true;
lock.notifyAll();
}
}
} catch (ThreadDeath td) {
// send angry message to client
// handle error without rethrowing td
}
监视线程:
synchronized (lock) {
while (! finished) {
try {
lock.wait(REGEX_TIMEOUT);
if (! finished) {
matcherThread.stop();
}
} catch (InterruptedException ex) {
// ignore, top level method in dedicated thread, etc..
}
}
}
我已经读过 java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html,我认为这种用法是安全的,因为我通过同步控制了ThreadDeath被抛出的位置并处理它,唯一损坏的对象可能是我的Pattern和Matcher实例,无论如何都会被丢弃。我认为这会破坏Thread.stop(),因为我没有重新抛出错误,但我真的不希望线程死亡,只需中止find()方法。
到目前为止,我已经设法避免使用这些已弃用的API组件,但是Matcher.find()似乎不可中断,可能需要很长时间才能返回。有没有更好的方法来做到这一点?