Debian Codegraph @

src/main/java/com/jcabi/aspects/aj/MethodScheduler.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.ScheduleWithFixedDelay;
33 import com.jcabi.log.Logger;
34 import com.jcabi.log.VerboseRunnable;
35 import com.jcabi.log.VerboseThreads;
36 import java.io.Closeable;
37 import java.io.IOException;
38 import java.util.concurrent.Callable;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.concurrent.ConcurrentMap;
41 import java.util.concurrent.Executors;
42 import java.util.concurrent.ScheduledExecutorService;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.atomic.AtomicLong;
45 import org.aspectj.lang.JoinPoint;
46 import org.aspectj.lang.annotation.After;
47 import org.aspectj.lang.annotation.Aspect;
48 import org.aspectj.lang.annotation.Before;
49
50 /**
51 * Schedules methods.
52 *
53 * @author Yegor Bugayenko ([email protected])
54 * @version $Id: 0a3ab248880d3777e10afc5718543d1c2369e83f $
55 * @since 0.7.16
56 */
57 @Aspect
58 @SuppressWarnings("PMD.DoNotUseThreads")
59 public final class MethodScheduler {
60
61 /**
62 * Objects and their running services.
63 */
64 private final transient
65 ConcurrentMap<Object, MethodScheduler.Service> services;
66
67 /**
68 * Ctor.
69 */
70 public MethodScheduler() {
71 this.services =
72 new ConcurrentHashMap<Object, MethodScheduler.Service>(0);
73 }
74
75 /**
76 * Instantiate a new routine task.
77 *
78 * <p>Try NOT to change the signature of this method, in order to keep
79 * it backward compatible.
80 *
81 * @param point Joint point
82 * @checkstyle LineLength (2 lines)
83 */
84 @After("initialization((@com.jcabi.aspects.ScheduleWithFixedDelay *).new(..))")
85 public void instantiate(final JoinPoint point) {
86 final Object object = point.getTarget();
87 if (this.services.containsKey(object)) {
88 throw new IllegalStateException(
89 Logger.format(
90 "%[type]s was already scheduled for execution",
91 object
92 )
93 );
94 }
95 Runnable runnable;
96 if (object instanceof Runnable) {
97 runnable = new VerboseRunnable(Runnable.class.cast(object), true);
98 } else if (object instanceof Callable) {
99 runnable = new VerboseRunnable(Callable.class.cast(object), true);
100 } else {
101 throw new IllegalStateException(
102 Logger.format(
103 "%[type]s doesn't implement Runnable or Callable",
104 object
105 )
106 );
107 }
108 this.services.put(
109 object,
110 new MethodScheduler.Service(
111 runnable,
112 object,
113 object.getClass().getAnnotation(ScheduleWithFixedDelay.class)
114 )
115 );
116 }
117
118 /**
119 * Stop/close a routine task.
120 *
121 * <p>Try NOT to change the signature of this method, in order to keep
122 * it backward compatible.
123 *
124 * @param point Joint point
125 * @throws IOException If can't close
126 * @checkstyle LineLength (2 lines)
127 */
128 @Before("execution(* (@com.jcabi.aspects.ScheduleWithFixedDelay *).close())")
129 public void close(final JoinPoint point) throws IOException {
130 final Object object = point.getTarget();
131 this.services.get(object).close();
132 this.services.remove(object);
133 }
134
135 /**
136 * Running service.
137 */
138 private static final class Service implements Closeable {
139 /**
140 * Running scheduled service.
141 */
142 private final transient ScheduledExecutorService executor;
143 /**
144 * The object.
145 */
146 private final transient Object object;
147 /**
148 * Execution counter.
149 */
150 private final transient AtomicLong counter;
151 /**
152 * When started.
153 */
154 private final transient long start;
155 /**
156 * How long to wait for the task to finish.
157 */
158 private final transient long await;
159 /**
160 * Shutdown attempts count.
161 */
162 private final transient long attempts;
163 /**
164 * Should more information be logged?
165 */
166 private final transient boolean verbose;
167 /**
168 * Public ctor.
169 * @param runnable The runnable to schedule
170 * @param obj Object
171 * @param annt Annotation
172 */
173 protected Service(final Runnable runnable, final Object obj,
174 final ScheduleWithFixedDelay annt) {
175 this.start = System.currentTimeMillis();
176 this.counter = new AtomicLong();
177 this.object = obj;
178 this.executor = Executors.newScheduledThreadPool(
179 annt.threads(),
180 new VerboseThreads(this.object)
181 );
182 this.verbose = annt.verbose();
183 this.await = annt.awaitUnit().toMillis(annt.await());
184 this.attempts = annt.shutdownAttempts();
185 final Runnable job = new Runnable() {
186 @Override
187 public void run() {
188 runnable.run();
189 MethodScheduler.Service.this.counter.incrementAndGet();
190 }
191 };
192 for (int thread = 0; thread < annt.threads(); ++thread) {
193 this.executor.scheduleWithFixedDelay(
194 job, annt.delay(), annt.delay(), annt.unit()
195 );
196 }
197 if (this.verbose) {
198 Logger.info(
199 this.object,
200 "scheduled for execution with %d %s interval",
201 annt.delay(),
202 annt.unit()
203 );
204 }
205 }
206 @Override
207 public void close() throws IOException {
208 this.executor.shutdown();
209 final long begin = System.currentTimeMillis();
210 try {
211 while (true) {
212 if (this.executor.awaitTermination(1, TimeUnit.SECONDS)) {
213 break;
214 }
215 final long age = System.currentTimeMillis() - begin;
216 if (age > this.await) {
217 break;
218 }
219 if (this.verbose) {
220 Logger.info(
221 this, "waiting %[ms]s for threads termination", age
222 );
223 }
224 }
225 for (int attempt = 0; attempt < this.attempts; ++attempt) {
226 this.executor.shutdownNow();
227 this.executor.awaitTermination(1, TimeUnit.SECONDS);
228 }
229 if (!this.executor.isTerminated()) {
230 throw new IllegalStateException(
231 Logger.format(
232 "failed to shutdown %[type]s of %[type]s",
233 this.executor,
234 this.object
235 )
236 );
237 }
238 } catch (final InterruptedException ex) {
239 Thread.currentThread().interrupt();
240 throw new IllegalStateException(ex);
241 }
242 if (this.verbose) {
243 Logger.info(
244 this.object,
245 "execution stopped after %[ms]s and %d tick(s)",
246 System.currentTimeMillis() - this.start,
247 this.counter.get()
248 );
249 }
250 }
251 }
252
253 }