How to set a time limit on a java function running a regex

后端 未结 10 845
难免孤独
难免孤独 2020-12-17 02:41

I am running a regex in a java function to parse a document and return true if it has found the string specified by the regex and return false if it hasn\'t. But the problem

10条回答
  •  隐瞒了意图╮
    2020-12-17 03:00

    I will assume for the moment that your regexp code is correct, and it really is some computational code that is CPU-bound for 6s.

    Given the above, I think you have only one option. To execute your code in a number of stages/iterations and check a variable for a request to halt. You can't do this using the normal Pattern/Matcher code.

    You could do this by splitting your input string beforehand in some fashion, and then feeding to your regexp bit by bit (your initial split would have to be independent of your regexp).

    You can't do this by:

    1. using Thread.stop() etc. This has been deprecated and doesn't work properly.
    2. Using Thread.interrupt(). This sets an interrupted flag on the thread which is only checked when the thread performs IO. If the thread is CPU-bound, then that flag will never be checked.

    Given the above, I would look again at why the regexp is taking 6s to match. Is the regexp correct ? Can you perform a regexp on smaller text segments ?

提交回复
热议问题