Search code examples
javagroovyinterrupt-handling

How to solve Groovy Unexpected input: @TimedInterrupt


I'm trying to execute the following groovy script by importing groovy class TimedInterrupt, unfortunately unable to comprehend the reason behind the compilation error. I have referred groovyOfficial documentation and have also looked at some resources here but could not make a significant progress. I would appreciate any valuable inputs from groovy experts in resolving this.

import groovy.transform.TimedInterrupt
import java.util.concurrent.TimeUnit

def buildInterrupt() {
    @TimedInterrupt(value = 3L, unit = TimeUnit.MICROSECONDS)
}

def timeout_method() {
    println 'This is for testing: '
}
 
buildInterrupt() //this invocation is necessary in the long run
time_method()

Post Execution
1 compilation error:

Unexpected input: '@TimedInterrupt(value = 3L, unit = TimeUnit.MICROSECONDS)\n}' at line: 6, column: 1

I need the timed interrupt to take effect and the expected output is below

Exception thrown

java.util.concurrent.TimeoutException: Execution timed out after 3 microseconds. Start time: Thu Mar 14 12:28:09 IST 2020
at timeout_method.run(timeout_method.groovy)

Thanks


Solution

  • I believe the reason you are running into compilation issues is that an annotation (TimedInterrupt in this case) needs to annotate a class, a member variable, a method, etc. In your case the annotation is applied in a location where it "has nothing to annotate".

    The following code:

    import groovy.transform.TimedInterrupt
    import java.util.concurrent.TimeUnit
    
    @TimedInterrupt(value = 500L, unit = TimeUnit.MILLISECONDS)
    def somethingToAnnotate = 0
    
    def methodA() {
      // sleep 100 ms
      100.times { Thread.sleep(1) }
      println 'hello from method a'
    }
    
    10.times { 
      methodA()
    }
    

    works and prints:

    ─➤ groovy solution.groovy
    hello from method a
    hello from method a
    hello from method a
    hello from method a
    Caught: java.util.concurrent.TimeoutException: Execution timed out after 500 milliseconds. Start time: Fri Mar 26 12:11:14 CET 2021
    java.util.concurrent.TimeoutException: Execution timed out after 500 milliseconds. Start time: Fri Mar 26 12:11:14 CET 2021
        at solution$_methodA_closure2.doCall(solution.groovy)
        at solution.methodA(solution.groovy:9)
        at solution$_run_closure1.doCall(solution.groovy:14)
        at solution.run(solution.groovy:13)
    
    ─➤
    

    Here the annotation is applied to a variable.

    It should be noted that in a groovy script, if you annotate a method, the timeout is started when the method is defined, not when it's executed. In other words, annotating a method and running the script will start the timeout even if the method is never run.