How can I make external methods interruptable?

后端 未结 8 1084
南旧
南旧 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:31

    You wrote:

    Another option I've tried is to mark myMethod() and similar methods with a special "Interruptable" annotation and then use AspectJ (which I am admittedly a newbie at) for catching all method invocations there - something like:

    @Before("call(* *.*(..)) && withincode(@Interruptable * *.*(..))")
    public void checkInterrupt(JoinPoint thisJoinPoint) {
        if (Thread.interrupted()) throw new ForcefulInterruption();
    }
    

    But withincode isn't recursive to methods called by the matching methods, so I would have to edit this annotation into the external code.

    The AspectJ idea is good, but you need to

    • use cflow() or cflowbelow() in order to recursively match a certain control flow (e.g. something like @Before("cflow(execution(@Interruptable * *(..)))")).
    • make sure to also weave your external library, not just you own code. This can be done by either using binary weaving, instrumenting the JAR file's classes and re-packaging them into a new JAR file, or by applying LTW (load-time weaving) during application start-up (i.e. during class loading).

    You might not even need your marker annotation if your external library has a package name you can pinpoint with within(). AspectJ is really powerful, and often there is more than one way to solve a problem. I would recommend using it because it was made for such endeavours as yours.

提交回复
热议问题