There is no safe way to stop a thread executing, unless it is being cooperative; e.g. it regularly checks the 'interrupted' flag.
@BobbyShaftoe suggests this in a comment:
You could execute this function in a separate thread and then abort the thread after some period of time.
This is misleading and dangerous advice. The only way to "abort" a thread is to use the deprecated Thread.stop()
method. If you look at the javadoc for that method you will see that it is a fundamentally dangerous method that is liable to have undesirable and unpredictable side-effects.
It should also be noted that @tonio's solution doesn't stop the function's execution. It simply stops waiting for the function's execution to finish. The function could continue executing indefinitely, chewing up resources to no good effect.