How can I make external methods interruptable?

后端 未结 8 915
南旧
南旧 2021-02-05 02:32

The Problem

I\'m running multiple invocations of some external method via an ExecutorService. I would like to be able to interrupt these methods, but unfortunately the

8条回答
  •  梦如初夏
    2021-02-05 03:13

    I have hacked an ugly solution to my problem. It's not pretty, but it works in my case, so I'm posting it here in case it will help anyone else.

    What I did was profile the library parts of my application, hoping that I could isolate a small group of methods which are called repeatedly - for example some get methods or equals() or something along these lines; and then I could insert the following code segment there:

    if (Thread.interrupted()) {
        // Not really necessary, but could help if the library does check it itself in some other place:
        Thread.currentThread().interrupt();
        // Wrapping the checked InterruptedException because the signature doesn't declare it:
        throw new RuntimeException(new InterruptedException());
    }
    

    Either inserting it manually by editing the library's code, or automatically by writing an appropriate aspect. Notice that if the library attempts to catch and swallow a RuntimeException, the thrown exception could be replaced with something else the library doesn't try to catch.

    Luckily for me, using VisualVM, I was able to find a single method called a very high number of times during the specific usage I was making of the library. After adding the above code segment, it now properly responds to interrupts.

    This is of course not maintainable, plus nothing really guarantees the library will call this method repeatedly in other scenarios; but it worked for me, and since it's relatively easy to profile other applications and insert the checks there, I consider this a generic, if ugly, solution.

提交回复
热议问题