小编And*_*eas的帖子

在Java中可以接受使用Thread#stop()来杀死正在运行的线程吗?

遗憾的是,在Java中对String使用正则表达式时无法指定超时.因此,如果您没有严格控制哪些模式应用于哪个输入,您可能最终会拥有消耗大量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 …
Run Code Online (Sandbox Code Playgroud)

java regex multithreading timeout

6
推荐指数
2
解决办法
640
查看次数

标签 统计

java ×1

multithreading ×1

regex ×1

timeout ×1