gpt4 book ai didi

java - 在 Java 中使用 Thread#stop() 来终止一个正在运行的线程是否可以接受?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:15 26 4
gpt4 key购买 nike

遗憾的是,在 Java 中对字符串使用正则表达式时无法指定超时。因此,如果您没有严格控制将哪些模式应用于哪些输入,您最终可能会拥有消耗大量 CPU 的线程,同时无休止地尝试将(设计不佳的)模式与(恶意的?)输入匹配。

我知道 Thread#stop() 被弃用的原因(参见 http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html )。它们以可能在 ThreadDeath 异常情况下损坏的对象为中心,然后这些对象会污染您正在运行的 JVM 环境并可能导致细微的错误。

对于比我对 JVM 的工作原理有更深入了解的任何人,我的问题是:如果需要停止的线程没有持有任何(明显的)监视器或对使用的对象的引用程序的其余部分,那么可以接受使用 Thread#stop() 吗?

我创建了一个相当防御性的解决方案,以便能够处理具有超时的正则表达式匹配。我很高兴收到任何评论或评论,尤其是关于这种方法可能导致的问题,尽管我努力避免这些问题。

谢谢!

import java.util.concurrent.Callable;

public class SafeRegularExpressionMatcher {

// demonstrates behavior for regular expression running into catastrophic backtracking for given input
public static void main(String[] args) {
SafeRegularExpressionMatcher matcher = new SafeRegularExpressionMatcher(
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "(x+x+)+y", 2000);
System.out.println(matcher.matches());
}

final String stringToMatch;

final String regularExpression;

final int timeoutMillis;

public SafeRegularExpressionMatcher(String stringToMatch, String regularExpression, int timeoutMillis) {
this.stringToMatch = stringToMatch;
this.regularExpression = regularExpression;
this.timeoutMillis = timeoutMillis;
}

public Boolean matches() {
CallableThread<Boolean> thread = createSafeRegularExpressionMatchingThread();
Boolean result = tryToGetResultFromThreadWithTimeout(thread);
return result;
}

private CallableThread<Boolean> createSafeRegularExpressionMatchingThread() {
final String stringToMatchForUseInThread = new String(stringToMatch);
final String regularExpressionForUseInThread = new String(regularExpression);
Callable<Boolean> callable = createRegularExpressionMatchingCallable(stringToMatchForUseInThread,
regularExpressionForUseInThread);
CallableThread<Boolean> thread = new CallableThread<Boolean>(callable);
return thread;
}

private Callable<Boolean> createRegularExpressionMatchingCallable(final String stringToMatchForUseInThread,
final String regularExpressionForUseInThread) {
Callable<Boolean> callable = new Callable<Boolean>() {
public Boolean call() throws Exception {
return Boolean.valueOf(stringToMatchForUseInThread.matches(regularExpressionForUseInThread));
}
};
return callable;
}

private Boolean tryToGetResultFromThreadWithTimeout(CallableThread<Boolean> thread) {
startThreadAndApplyTimeout(thread);
Boolean result = processThreadResult(thread);
return result;
}

private void startThreadAndApplyTimeout(CallableThread<Boolean> thread) {
thread.start();
try {
thread.join(timeoutMillis);
} catch (InterruptedException e) {
throwRuntimeException("Interrupt", e);
}
}

private Boolean processThreadResult(CallableThread<Boolean> thread) {
Boolean result = null;
if (thread.isAlive()) {
killThread(thread); // do not use anything from the thread anymore, objects may be damaged!
throwRuntimeException("Timeout", null);
} else {
Exception exceptionOccurredInThread = thread.getException();
if (exceptionOccurredInThread != null) {
throwRuntimeException("Exception", exceptionOccurredInThread);
} else {
result = thread.getResult();
}
}
return result;
}

private void throwRuntimeException(String situation, Exception e) {
throw new RuntimeException(situation + " occured while applying pattern /" + regularExpression + "/ to input '"
+ stringToMatch + " after " + timeoutMillis + "ms!", e);
}

/**
* This method uses {@link Thread#stop()} to kill a thread that is running wild. Although it is acknowledged that
* {@link Thread#stop()} is inherently unsafe, the assumption is that the thread to kill does not hold any monitors on or
* even references to objects referenced by the rest of the JVM, so it is acceptable to do this.
*
* After calling this method nothing from the thread should be used anymore!
*
* @param thread Thread to stop
*/
@SuppressWarnings("deprecation")
private static void killThread(CallableThread<Boolean> thread) {
thread.stop();
}

private static class CallableThread<V> extends Thread {

private final Callable<V> callable;

private V result = null;

private Exception exception = null;

public CallableThread(Callable<V> callable) {
this.callable = callable;
}

@Override
public void run() {
try {
V result = compute();
setResult(result);
} catch (Exception e) {
exception = e;
} catch (ThreadDeath e) {
cleanup();
}
}

private V compute() throws Exception {
return callable.call();
}

private synchronized void cleanup() {
result = null;
}

private synchronized void setResult(V result) {
this.result = result;
}

public synchronized V getResult() {
return result;
}

public synchronized Exception getException() {
return exception;
}

}

}

编辑:

感谢 dawce 将我指向 this solution我已经能够在不需要额外线程的情况下解决我原来的问题。我已经在那里发布了代码。感谢所有回复的人。

最佳答案

如果您确定 Thread.stop() 是您唯一可用的解决方案,则可以使用它。您可能需要关闭并重新启动您的应用程序以确保其处于良好状态。

注意:线程可以捕获并忽略 ThreadDeath,因此不能保证停止所有线程。

另一种停止线程的方法是在不同的进程中运行它。这可以根据需要被杀死。这仍然会使资源处于不一致的状态(如锁定文件),但这种情况不太可能也更容易控制。

当然,最好的解决方案是修复代码,使其一开始就不会这样做,而是尊重 Thread.interrupt()。

关于java - 在 Java 中使用 Thread#stop() 来终止一个正在运行的线程是否可以接受?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11307649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com