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

后端 未结 10 938
难免孤独
难免孤独 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:03

    The Java Thread class is not equipped to deal with this sort of interruption, and as such is not suitable for your requirements.

    I would implement the functionality in a separate Process using the ProcessBuilder and use the Input and Output streams provided by the Process class for communication. Forceful interruption is provided by the destroy method of of the Process class.

    I believe this is the correct, safest, implementation for the requirements you have. Unfortunately, Java doesn't make it easy to launch another Java process in a platform independent way so you'll have to have the java executable to your path and create a separate main method to do this. This is harder than it should be.

提交回复
热议问题