假设我正在运行一项服务,用户可以提交正则表达式来搜索大量数据.如果用户提交一个非常慢的正则表达式(即,需要几分钟才能返回Matcher.find()),我想要一种方法来取消该匹配.我能想到这样做的唯一方法是让另一个线程监视匹配的持续时间,并在必要时使用Thread.stop()取消它.
成员变量:
long REGEX_TIMEOUT = 30000L;
Object lock = new Object();
boolean finished = false;
Thread matcherThread;
Run Code Online (Sandbox Code Playgroud)
匹配线程:
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
}
Run Code Online (Sandbox Code Playgroud)
监控线程:
synchronized (lock) {
while (! finished) {
try {
lock.wait(REGEX_TIMEOUT);
if (! …Run Code Online (Sandbox Code Playgroud)