Search code examples
javabytecodeexecution-timedeterministic

Time deterministic execution of Runnable


Given a Runnable object e.g.

public class Test implements Runnable {

    @Override
    public void run() {

        int x = 2;
        int y = 6;
        // Snip more code
        int w = x - 1;
        int z = x * y;          

    }

}

I'd like to be able to execute an exact number of operations e.g.

Test t = new Test();
Executor.execute(t, 100); // Arbitrary unit of operations

Such that if the first time I do this execution runs up to:

int w = x - 1;

Any other time I call the method with the same parameters will result in execution up to the same point.

I've had a look around and can't see anything suitable (e.g. ScheduledThreadPoolExecutor won't work as far as I can tell).

Will I have to move to the bytecode level to make this worK? From what I've read the JIT may cause problems here too.


Solution

  • You can inject byte code so that it check the timeout after every operation. This could make it 100x slower or more, but it would be deterministic.

    A more pragmatic apporach would be to check the timeout at inveals of your chosing by adding code to the Runnable.