Posted By

Cur3n4 on 10/01/11


Tagged


Versions (?)

Answer question 1


 / Published in: Java
 

The idea is to create a proxy class that will delegate the increment and decrement call to MyIncDec implementation while measuring the time. To make it as transparent as possible, the proxy extends the IncDec interface. Beacuse a dependency to the actual IncDec implementation is required, the proxy constructor requires this implementation to be passed in as a parameter. Furthermore, the code of the increment and decrement methods will still measure the duration even if an exception is thrown.

Because time measuring (performance analysis) is a cross cutting concern in a real system I would use AOP to define the timing logic just once and apply it to any method as required.

  1. public class IncDecTimerAdapter implements IncDec {
  2.  
  3. private static Logger logger = ...;
  4. private final IncDec incDecToTime;
  5.  
  6. public IncDecTimerAdapter(IncDec incDecToTime) {
  7. this.incDecToTime = incDecToTime;
  8. }
  9.  
  10. public void increment() {
  11. long start = System.currentTimeMillis();
  12. try {
  13. incDecToTime.increment();
  14. } finally {
  15. long duration = System.currentTimeMillis() - start;
  16. logger.debug("Time to increment: %0 (in millis)", duration);
  17. }
  18. }
  19.  
  20. public void decrement() {
  21. long start = System.currentTimeMillis();
  22. try {
  23. incDecToTime.decrement();
  24. } finally {
  25. long duration = System.currentTimeMillis() - start;
  26. logger.debug("Time to decrement: %0 (in millis)", duration);
  27. }
  28. }
  29. }

Report this snippet  

You need to login to post a comment.