blob: eb9e15315105c7d514429d7f5796174f674df5ac (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
== Pitfalls
[[pitfalls-intro]]
=== Introduction
This chapter consists of a few AspectJ programs that may lead to
surprising behavior and how to understand them.
[[pitfalls-infiniteLoops]]
=== Infinite loops
Here is a Java program with peculiar behavior
[source, java]
....
public class Main {
public static void main(String[] args) {
foo();
System.out.println("done with call to foo");
}
static void foo() {
try {
foo();
} finally {
foo();
}
}
}
....
This program will never reach the `println` call, but when it aborts may
have no stack trace.
This silence is caused by multiple ``StackOverflowException``s. First the
infinite loop in the body of the method generates one, which the finally
clause tries to handle. But this finally clause also generates an
infinite loop which the current JVMs can't handle gracefully leading to
the completely silent abort.
The following short aspect will also generate this behavior:
[source, java]
....
aspect A {
before(): call(* *(..)) { System.out.println("before"); }
after(): call(* *(..)) { System.out.println("after"); }
}
....
Why? Because the call to println is also a call matched by the pointcut
`call (* *(..))`. We get no output because we used simple `after()`
advice. If the aspect were changed to
[source, java]
....
aspect A {
before(): call(* *(..)) { System.out.println("before"); }
after() returning: call(* *(..)) { System.out.println("after"); }
}
....
then at least a `StackOverflowException` with a stack trace would be seen.
In both cases, though, the overall problem is advice applying within its
own body.
There's a simple idiom to use if you ever have a worry that your advice
might apply in this way. Just restrict the advice from occurring in join
points caused within the aspect. So:
[source, java]
....
aspect A {
before(): call(* *(..)) && !within(A) { System.out.println("before"); }
after() returning: call(* *(..)) && !within(A) { System.out.println("after"); }
}
....
Other solutions might be to more closely restrict the pointcut in other
ways, for example:
[source, java]
....
aspect A {
before(): call(* MyObject.*(..)) { System.out.println("before"); }
after() returning: call(* MyObject.*(..)) { System.out.println("after"); }
}
....
The moral of the story is that unrestricted generic pointcuts can pick
out more join points than intended.
|