You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Useful1.java 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Exploring synchronization
  2. aspect WithinAspect {
  3. long locktimer = 0;
  4. int iterations = 0;
  5. Object currentObject = null;
  6. boolean didSomething = false;
  7. long activeTimer;
  8. before(Object o ): within(Useful1) && args(o) {
  9. if (thisJoinPoint.getSignature().toString().startsWith("lock(")) {
  10. activeTimer = System.currentTimeMillis();
  11. didSomething = true;
  12. }
  13. }
  14. after(Object o ): within(Useful1) && args(o) {
  15. if (thisJoinPoint.getSignature().toString().startsWith("unlock(")) {
  16. if (activeTimer!=0) {
  17. locktimer+=(System.currentTimeMillis()-activeTimer);
  18. iterations++;
  19. activeTimer=0;
  20. didSomething = true;
  21. }
  22. }
  23. }
  24. after() returning: execution(* main(..)) {
  25. System.err.println("Average lock taking time over "+iterations+" iterations is "+
  26. (((double)locktimer)/
  27. ((double)iterations))+"ms");
  28. if (didSomething) System.err.println("We did time something!"); // can write a test looking for this line, it won't vary
  29. }
  30. }
  31. public class Useful1 {
  32. public static void main(String[] args) {
  33. Useful1 u = new Useful1();
  34. for (int i = 0; i < 2000; i++) {
  35. u.methodWithSynchronizedBlock();
  36. }
  37. }
  38. public void methodWithSynchronizedBlock() {
  39. synchronized (this) {
  40. for (int ii=0;ii<100;ii++);
  41. }
  42. }
  43. }