Debian Codegraph @

src/main/java/com/jcabi/aspects/aj/MethodInterrupter.java

raw
1 /**
2 * Copyright (c) 2012-2017, jcabi.com
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met: 1) Redistributions of source code must retain the above
8 * copyright notice, this list of conditions and the following
9 * disclaimer. 2) Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution. 3) Neither the name of the jcabi.com nor
13 * the names of its contributors may be used to endorse or promote
14 * products derived from this software without specific prior written
15 * permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28 * OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30 package com.jcabi.aspects.aj;
31
32 import com.jcabi.aspects.Timeable;
33 import com.jcabi.log.Logger;
34 import com.jcabi.log.VerboseRunnable;
35 import java.lang.reflect.Method;
36 import java.util.Set;
37 import java.util.concurrent.ConcurrentSkipListSet;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.TimeUnit;
41 import org.aspectj.lang.ProceedingJoinPoint;
42 import org.aspectj.lang.annotation.Around;
43 import org.aspectj.lang.annotation.Aspect;
44 import org.aspectj.lang.reflect.MethodSignature;
45
46 /**
47 * Interrupts long-running methods.
48 *
49 * <p>It is an AspectJ aspect and you are not supposed to use it directly. It
50 * is instantiated by AspectJ runtime framework when your code is annotated
51 * with {@link Timeable} annotation.
52 *
53 * <p>The class is thread-safe.
54 *
55 * @author Yegor Bugayenko ([email protected])
56 * @version $Id: 24269a432c18838ffd313f445e10900d62cb018c $
57 * @since 0.7.16
58 */
59 @Aspect
60 @SuppressWarnings("PMD.DoNotUseThreads")
61 public final class MethodInterrupter {
62
63 /**
64 * Calls being watched.
65 */
66 private final transient Set<MethodInterrupter.Call> calls;
67
68 /**
69 * Service that interrupts threads.
70 */
71 private final transient ScheduledExecutorService interrupter;
72
73 /**
74 * Public ctor.
75 */
76 public MethodInterrupter() {
77 this.calls = new ConcurrentSkipListSet<MethodInterrupter.Call>();
78 this.interrupter = Executors.newSingleThreadScheduledExecutor(
79 new NamedThreads(
80 "timeable",
81 "interrupting of @Timeable annotated methods"
82 )
83 );
84 this.interrupter.scheduleWithFixedDelay(
85 new VerboseRunnable(
86 new Runnable() {
87 @Override
88 public void run() {
89 MethodInterrupter.this.interrupt();
90 }
91 }
92 ),
93 1, 1, TimeUnit.SECONDS
94 );
95 }
96
97 /**
98 * Run and interrupt a method, if stuck.
99 *
100 * <p>Try NOT to change the signature of this method, in order to keep
101 * it backward compatible.
102 *
103 * @param point Joint point
104 * @return The result of call
105 * @throws Throwable If something goes wrong inside
106 * @checkstyle IllegalThrows (5 lines)
107 */
108 @Around("execution(* * (..)) && @annotation(com.jcabi.aspects.Timeable)")
109 @SuppressWarnings("PMD.AvoidCatchingThrowable")
110 public Object wrap(final ProceedingJoinPoint point) throws Throwable {
111 final MethodInterrupter.Call call = new MethodInterrupter.Call(point);
112 this.calls.add(call);
113 Object output;
114 try {
115 output = point.proceed();
116 } finally {
117 this.calls.remove(call);
118 }
119 return output;
120 }
121
122 /**
123 * Interrupt threads when needed.
124 */
125 private void interrupt() {
126 synchronized (this.interrupter) {
127 for (final MethodInterrupter.Call call : this.calls) {
128 if (call.expired() && call.interrupted()) {
129 this.calls.remove(call);
130 }
131 }
132 }
133 }
134
135 /**
136 * A call being watched.
137 */
138 private static final class Call implements
139 Comparable<MethodInterrupter.Call> {
140 /**
141 * The thread called.
142 */
143 private final transient Thread thread;
144 /**
145 * When started.
146 */
147 private final transient long start;
148 /**
149 * When will expire.
150 */
151 private final transient long deadline;
152 /**
153 * Join point.
154 */
155 private final transient ProceedingJoinPoint point;
156 /**
157 * Public ctor.
158 * @param pnt Joint point
159 */
160 public Call(final ProceedingJoinPoint pnt) {
161 this.thread = Thread.currentThread();
162 this.start = System.currentTimeMillis();
163 this.point = pnt;
164 final Method method = MethodSignature.class
165 .cast(pnt.getSignature())
166 .getMethod();
167 final Timeable annt = method.getAnnotation(Timeable.class);
168 this.deadline = this.start + annt.unit().toMillis(annt.limit());
169 }
170 @Override
171 public int compareTo(final Call obj) {
172 int compare;
173 if (this.deadline > obj.deadline) {
174 compare = 1;
175 } else if (this.deadline < obj.deadline) {
176 compare = -1;
177 } else {
178 compare = 0;
179 }
180 return compare;
181 }
182 /**
183 * Is it expired already?
184 * @return TRUE if expired
185 */
186 public boolean expired() {
187 return this.deadline < System.currentTimeMillis();
188 }
189 /**
190 * This thread is stopped already (interrupt if not)?
191 * @return TRUE if it's already dead
192 */
193 public boolean interrupted() {
194 boolean dead;
195 if (this.thread.isAlive()) {
196 this.thread.interrupt();
197 final Method method = MethodSignature.class
198 .cast(this.point.getSignature())
199 .getMethod();
200 Logger.warn(
201 method.getDeclaringClass(),
202 "%s: interrupted on %[ms]s timeout (over %[ms]s)",
203 Mnemos.toText(this.point, true, false),
204 System.currentTimeMillis() - this.start,
205 this.deadline - this.start
206 );
207 dead = false;
208 } else {
209 dead = true;
210 }
211 return dead;
212 }
213 }
214
215 }