0

I have an interface with three method start()、 rollback() and retry(),and the interface may has many implements assume two FisrtImpl and SecondImpl,how to record FisrtImpl and SecondImpl's start()、 rollback() and retry() time cost?

I find the likely questionRecord every method execution,but the answer not what i want.

TongChen
  • 1,414
  • 1
  • 11
  • 21

1 Answers1

0

Write a proxy implementation that times the methods.

public class FooTiming implements Foo {
    private final Foo foo;
    private long startTime;
    private long rollbackTime;
    private long retryTime;
    public FooTiming(Foo foo) {
        this.foo = foo;
    }
    @Override
    public void start() {
        long enter = System.nanoTime();
        this.foo.start();
        long exit = System.nanoTime();
        this.startTime += exit - enter;
    }
    @Override
    public void rollback() {
        long enter = System.nanoTime();
        this.foo.rollback();
        long exit = System.nanoTime();
        this.rollbackTime += exit - enter;
    }
    @Override
    public void retry() {
        long enter = System.nanoTime();
        this.foo.retry();
        long exit = System.nanoTime();
        this.retryTime += exit - enter;
    }
    @Override
    public String toString() {
        return String.format("start = %.3f ms, rollback = %.3f ms, retry = %.3f ms",
                             this.startTime / 1e6, this.rollbackTime / 1e6, this.retryTime / 1e6);
    }
}

Test

interface Foo {
    void start();
    void rollback();
    void retry();
}
class FirstImpl implements Foo {
    @Override public void start()    { try { Thread.sleep(200); } catch (InterruptedException ignored) {} }
    @Override public void rollback() { try { Thread.sleep(150); } catch (InterruptedException ignored) {} }
    @Override public void retry()    { try { Thread.sleep(170); } catch (InterruptedException ignored) {} }
}
class SecondImpl implements Foo {
    @Override public void start()    { try { Thread.sleep(120); } catch (InterruptedException ignored) {} }
    @Override public void rollback() { try { Thread.sleep(140); } catch (InterruptedException ignored) {} }
    @Override public void retry()    { try { Thread.sleep(160); } catch (InterruptedException ignored) {} }
}
public static void main(String[] args) {
    test("FirstImpl", new FirstImpl());
    test("SecondImpl", new SecondImpl());
}
private static void test(String name, Foo foo) {
    FooTiming timing = new FooTiming(foo);
    timing.start();
    timing.rollback();
    timing.retry();
    System.out.println(name + ": " + timing);
}

Output

FirstImpl: start = 201.505 ms, rollback = 150.611 ms, retry = 170.358 ms
SecondImpl: start = 122.426 ms, rollback = 140.017 ms, retry = 160.381 ms
Andreas
  • 154,647
  • 11
  • 152
  • 247