| 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.Cacheable; |
| 33 |
import com.jcabi.aspects.Loggable; |
| 34 |
import com.jcabi.log.Logger; |
| 35 |
import java.lang.ref.SoftReference; |
| 36 |
import java.lang.reflect.Method; |
| 37 |
import java.lang.reflect.Modifier; |
| 38 |
import java.util.Arrays; |
| 39 |
import java.util.concurrent.BlockingQueue; |
| 40 |
import java.util.concurrent.ConcurrentHashMap; |
| 41 |
import java.util.concurrent.ConcurrentMap; |
| 42 |
import java.util.concurrent.LinkedBlockingQueue; |
| 43 |
import java.util.concurrent.atomic.AtomicInteger; |
| 44 |
import org.aspectj.lang.JoinPoint; |
| 45 |
import org.aspectj.lang.ProceedingJoinPoint; |
| 46 |
import org.aspectj.lang.annotation.After; |
| 47 |
import org.aspectj.lang.annotation.Around; |
| 48 |
import org.aspectj.lang.annotation.Aspect; |
| 49 |
import org.aspectj.lang.annotation.Before; |
| 50 |
import org.aspectj.lang.reflect.MethodSignature; |
| 51 |
|
| 52 |
/** |
| 53 |
* Cache method results. |
| 54 |
* |
| 55 |
* <p>It is an AspectJ aspect and you are not supposed to use it directly. It |
| 56 |
* is instantiated by AspectJ runtime framework when your code is annotated |
| 57 |
* with {@link Cacheable} annotation. |
| 58 |
* |
| 59 |
* <p>The class is thread-safe. |
| 60 |
* |
| 61 |
* @author Yegor Bugayenko ([email protected]) |
| 62 |
* @version $Id: 81af9dfb282bbcda540b9148c81ef09cf1cd0199 $ |
| 63 |
* @since 0.8 |
| 64 |
*/ |
| 65 |
@Aspect |
| 66 |
@SuppressWarnings("PMD.TooManyMethods") |
| 67 |
public final class MethodCacher { |
| 68 |
|
| 69 |
/** |
| 70 |
* Calling tunnels. |
| 71 |
*/ |
| 72 |
private final transient |
| 73 |
ConcurrentMap<MethodCacher.Key, MethodCacher.Tunnel> tunnels; |
| 74 |
|
| 75 |
/** |
| 76 |
* Save the keys of caches which need update. |
| 77 |
*/ |
| 78 |
private final transient BlockingQueue<Key> updatekeys; |
| 79 |
|
| 80 |
/** |
| 81 |
* Public ctor. |
| 82 |
*/ |
| 83 |
public MethodCacher() { |
| 84 |
this.tunnels = |
| 85 |
new ConcurrentHashMap<MethodCacher.Key, MethodCacher.Tunnel>(0); |
| 86 |
this.updatekeys = |
| 87 |
new LinkedBlockingQueue<MethodCacher.Key>(); |
| 88 |
new UpdateMethodCacher(this.tunnels, this.updatekeys).start(); |
| 89 |
} |
| 90 |
|
| 91 |
/** |
| 92 |
* Call the method or fetch from cache. |
| 93 |
* |
| 94 |
* <p>Try NOT to change the signature of this method, in order to keep |
| 95 |
* it backward compatible. |
| 96 |
* |
| 97 |
* @param point Joint point |
| 98 |
* @return The result of call |
| 99 |
* @throws Throwable If something goes wrong inside |
| 100 |
* @checkstyle IllegalThrows (4 lines) |
| 101 |
*/ |
| 102 |
@Around("execution(* *(..)) && @annotation(com.jcabi.aspects.Cacheable)") |
| 103 |
public Object cache(final ProceedingJoinPoint point) throws Throwable { |
| 104 |
final MethodCacher.Key key = new MethodCacher.Key(point); |
| 105 |
MethodCacher.Tunnel tunnel; |
| 106 |
final Method method = MethodSignature.class |
| 107 |
.cast(point.getSignature()) |
| 108 |
.getMethod(); |
| 109 |
final Cacheable annot = method.getAnnotation(Cacheable.class); |
| 110 |
synchronized (this.tunnels) { |
| 111 |
for (final Class<?> before : annot.before()) { |
| 112 |
final boolean flag = Boolean.class.cast( |
| 113 |
before.getMethod("flushBefore").invoke(method.getClass()) |
| 114 |
); |
| 115 |
if (flag) { |
| 116 |
this.preflush(point); |
| 117 |
} |
| 118 |
} |
| 119 |
tunnel = this.tunnels.get(key); |
| 120 |
if (this.isCreateTunnel(tunnel)) { |
| 121 |
tunnel = new MethodCacher.Tunnel( |
| 122 |
point, key, annot.asyncUpdate() |
| 123 |
); |
| 124 |
this.tunnels.put(key, tunnel); |
| 125 |
} |
| 126 |
if (tunnel.expired() && tunnel.asyncUpdate()) { |
| 127 |
this.updatekeys.offer(key); |
| 128 |
} |
| 129 |
for (final Class<?> after : annot.after()) { |
| 130 |
final boolean flag = Boolean.class.cast( |
| 131 |
after.getMethod("flushAfter").invoke(method.getClass()) |
| 132 |
); |
| 133 |
if (flag) { |
| 134 |
this.postflush(point); |
| 135 |
} |
| 136 |
} |
| 137 |
} |
| 138 |
return tunnel.through(); |
| 139 |
} |
| 140 |
|
| 141 |
/** |
| 142 |
* Flush cache. |
| 143 |
* @param point Join point |
| 144 |
* @return Value of the method |
| 145 |
* @since 0.7.14 |
| 146 |
* @deprecated Since 0.7.17, and preflush() should be used |
| 147 |
* @throws Throwable If something goes wrong inside |
| 148 |
* @checkstyle IllegalThrows (3 lines) |
| 149 |
*/ |
| 150 |
@Deprecated |
| 151 |
public Object flush(final ProceedingJoinPoint point) throws Throwable { |
| 152 |
this.preflush(point); |
| 153 |
return point.proceed(); |
| 154 |
} |
| 155 |
|
| 156 |
/** |
| 157 |
* Flush cache. |
| 158 |
* |
| 159 |
* <p>Try NOT to change the signature of this method, in order to keep |
| 160 |
* it backward compatible. |
| 161 |
* |
| 162 |
* @param point Joint point |
| 163 |
* @since 0.7.14 |
| 164 |
*/ |
| 165 |
@Before |
| 166 |
( |
| 167 |
// @checkstyle StringLiteralsConcatenation (3 lines) |
| 168 |
"execution(* *(..))" |
| 169 |
+ " && (@annotation(com.jcabi.aspects.Cacheable.Flush)" |
| 170 |
+ " || @annotation(com.jcabi.aspects.Cacheable.FlushBefore))" |
| 171 |
) |
| 172 |
public void preflush(final JoinPoint point) { |
| 173 |
this.flush(point, "before the call"); |
| 174 |
} |
| 175 |
|
| 176 |
/** |
| 177 |
* Flush cache after method execution. |
| 178 |
* |
| 179 |
* <p>Try NOT to change the signature of this method, in order to keep |
| 180 |
* it backward compatible. |
| 181 |
* |
| 182 |
* @param point Joint point |
| 183 |
* @since 0.7.18 |
| 184 |
*/ |
| 185 |
@After |
| 186 |
( |
| 187 |
// @checkstyle StringLiteralsConcatenation (2 lines) |
| 188 |
"execution(* *(..))" |
| 189 |
+ " && @annotation(com.jcabi.aspects.Cacheable.FlushAfter)" |
| 190 |
) |
| 191 |
public void postflush(final JoinPoint point) { |
| 192 |
this.flush(point, "after the call"); |
| 193 |
} |
| 194 |
|
| 195 |
/** |
| 196 |
* Flush cache. |
| 197 |
* @param point Joint point |
| 198 |
* @param when When it happens |
| 199 |
* @since 0.7.18 |
| 200 |
*/ |
| 201 |
private void flush(final JoinPoint point, final String when) { |
| 202 |
synchronized (this.tunnels) { |
| 203 |
for (final MethodCacher.Key key : this.tunnels.keySet()) { |
| 204 |
if (!key.sameTarget(point)) { |
| 205 |
continue; |
| 206 |
} |
| 207 |
final MethodCacher.Tunnel removed = this.tunnels.remove(key); |
| 208 |
final Method method = MethodSignature.class |
| 209 |
.cast(point.getSignature()) |
| 210 |
.getMethod(); |
| 211 |
if (LogHelper.enabled( |
| 212 |
key.getLevel(), method.getDeclaringClass() |
| 213 |
)) { |
| 214 |
LogHelper.log( |
| 215 |
key.getLevel(), |
| 216 |
method.getDeclaringClass(), |
| 217 |
"%s: %s:%s removed from cache %s", |
| 218 |
Mnemos.toText(method, point.getArgs(), true, false), |
| 219 |
key, |
| 220 |
removed, |
| 221 |
when |
| 222 |
); |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
/** |
| 229 |
* Whether create a new Tunnel. |
| 230 |
* @param tunnel MethodCacher.Tunnel |
| 231 |
* @return Boolean |
| 232 |
*/ |
| 233 |
private boolean isCreateTunnel(final MethodCacher.Tunnel tunnel) { |
| 234 |
return tunnel == null || (tunnel.expired() && !tunnel.asyncUpdate()); |
| 235 |
} |
| 236 |
|
| 237 |
/** |
| 238 |
* Mutable caching/calling tunnel, it is thread-safe. |
| 239 |
*/ |
| 240 |
protected static final class Tunnel { |
| 241 |
/** |
| 242 |
* Proceeding join point. |
| 243 |
*/ |
| 244 |
private final transient ProceedingJoinPoint point; |
| 245 |
/** |
| 246 |
* Key related to this tunnel. |
| 247 |
*/ |
| 248 |
private final transient MethodCacher.Key key; |
| 249 |
/** |
| 250 |
* Whether asynchronous update. |
| 251 |
*/ |
| 252 |
private final transient boolean async; |
| 253 |
/** |
| 254 |
* Was it already executed? |
| 255 |
*/ |
| 256 |
private transient boolean executed; |
| 257 |
/** |
| 258 |
* When will it expire (moment in time). |
| 259 |
*/ |
| 260 |
private transient long lifetime; |
| 261 |
/** |
| 262 |
* Has non-null result? |
| 263 |
*/ |
| 264 |
private transient boolean hasresult; |
| 265 |
/** |
| 266 |
* Cached value. |
| 267 |
*/ |
| 268 |
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName") |
| 269 |
private transient SoftReference<Object> cached; |
| 270 |
|
| 271 |
/** |
| 272 |
* Public ctor. |
| 273 |
* @param pnt ProceedingJoinPoint |
| 274 |
* @param akey MethodCacher.Key |
| 275 |
* @param asy Boolean |
| 276 |
*/ |
| 277 |
Tunnel(final ProceedingJoinPoint pnt, |
| 278 |
final MethodCacher.Key akey, final boolean asy) { |
| 279 |
this.point = pnt; |
| 280 |
this.key = akey; |
| 281 |
this.async = asy; |
| 282 |
} |
| 283 |
|
| 284 |
@Override |
| 285 |
public String toString() { |
| 286 |
return Mnemos.toText(this.cached.get(), true, false); |
| 287 |
} |
| 288 |
|
| 289 |
/** |
| 290 |
* Get a new instance. |
| 291 |
* @return MethodCacher.Tunnel |
| 292 |
*/ |
| 293 |
public Tunnel copy() { |
| 294 |
return new Tunnel( |
| 295 |
this.point, this.key, this.async |
| 296 |
); |
| 297 |
} |
| 298 |
/** |
| 299 |
* Get a result through the tunnel. |
| 300 |
* @return The result |
| 301 |
* @throws Throwable If something goes wrong inside |
| 302 |
* @checkstyle IllegalThrows (5 lines) |
| 303 |
*/ |
| 304 |
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel") |
| 305 |
public synchronized Object through() throws Throwable { |
| 306 |
if (!this.executed) { |
| 307 |
final long start = System.currentTimeMillis(); |
| 308 |
final Object result = this.point.proceed(); |
| 309 |
this.hasresult = result != null; |
| 310 |
this.cached = new SoftReference<Object>(result); |
| 311 |
final Method method = MethodSignature.class |
| 312 |
.cast(this.point.getSignature()) |
| 313 |
.getMethod(); |
| 314 |
final Cacheable annot = method.getAnnotation(Cacheable.class); |
| 315 |
final String suffix; |
| 316 |
if (annot.forever()) { |
| 317 |
this.lifetime = Long.MAX_VALUE; |
| 318 |
suffix = "valid forever"; |
| 319 |
} else if (annot.lifetime() == 0) { |
| 320 |
this.lifetime = 0L; |
| 321 |
suffix = "invalid immediately"; |
| 322 |
} else { |
| 323 |
final long msec = annot.unit().toMillis( |
| 324 |
(long) annot.lifetime() |
| 325 |
); |
| 326 |
this.lifetime = start + msec; |
| 327 |
suffix = Logger.format("valid for %[ms]s", msec); |
| 328 |
} |
| 329 |
final Class<?> type = method.getDeclaringClass(); |
| 330 |
if (LogHelper.enabled(this.key.getLevel(), type)) { |
| 331 |
LogHelper.log( |
| 332 |
this.key.getLevel(), |
| 333 |
type, |
| 334 |
"%s: %s cached in %[ms]s, %s", |
| 335 |
Mnemos.toText( |
| 336 |
method, this.point.getArgs(), true, false |
| 337 |
), |
| 338 |
Mnemos.toText(this.cached.get(), true, false), |
| 339 |
System.currentTimeMillis() - start, |
| 340 |
suffix |
| 341 |
); |
| 342 |
} |
| 343 |
this.executed = true; |
| 344 |
} |
| 345 |
return this.key.through(this.cached.get()); |
| 346 |
} |
| 347 |
/** |
| 348 |
* Is it expired already? |
| 349 |
* @return TRUE if expired |
| 350 |
*/ |
| 351 |
public boolean expired() { |
| 352 |
final boolean expired = this.lifetime < System.currentTimeMillis(); |
| 353 |
final boolean collected = this.executed |
| 354 |
&& this.hasresult |
| 355 |
&& this.cached.get() == null; |
| 356 |
return this.executed && (expired || collected); |
| 357 |
} |
| 358 |
|
| 359 |
/** |
| 360 |
* Whether asynchronous update. |
| 361 |
* @return TRUE if asynchronous update |
| 362 |
*/ |
| 363 |
public boolean asyncUpdate() { |
| 364 |
return this.async; |
| 365 |
} |
| 366 |
|
| 367 |
/** |
| 368 |
* Soft reference to cached object. |
| 369 |
* Visible only for testing. Do not use directly. |
| 370 |
* @return Soft reference to cached object. |
| 371 |
*/ |
| 372 |
@SuppressWarnings("PMD.DefaultPackage") |
| 373 |
SoftReference<Object> cached() { |
| 374 |
return this.cached; |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
/** |
| 379 |
* Key of a callable target. |
| 380 |
* @checkstyle DesignForExtensionCheck (2 lines) |
| 381 |
*/ |
| 382 |
protected static class Key { |
| 383 |
/** |
| 384 |
* When instantiated. |
| 385 |
*/ |
| 386 |
private final transient long start; |
| 387 |
/** |
| 388 |
* How many times the key was already accessed. |
| 389 |
*/ |
| 390 |
private final transient AtomicInteger accessed; |
| 391 |
/** |
| 392 |
* Method. |
| 393 |
*/ |
| 394 |
private final transient Method method; |
| 395 |
/** |
| 396 |
* Object callable (or class, if static method). |
| 397 |
*/ |
| 398 |
private final transient Object target; |
| 399 |
/** |
| 400 |
* Arguments. |
| 401 |
*/ |
| 402 |
private final transient Object[] arguments; |
| 403 |
|
| 404 |
/** |
| 405 |
* Log level. |
| 406 |
*/ |
| 407 |
private final int level; |
| 408 |
|
| 409 |
/** |
| 410 |
* Public ctor. |
| 411 |
* @param point Joint point |
| 412 |
*/ |
| 413 |
Key(final JoinPoint point) { |
| 414 |
this.start = System.currentTimeMillis(); |
| 415 |
this.accessed = new AtomicInteger(); |
| 416 |
this.method = MethodSignature.class |
| 417 |
.cast(point.getSignature()).getMethod(); |
| 418 |
this.target = MethodCacher.Key.targetize(point); |
| 419 |
this.arguments = point.getArgs(); |
| 420 |
if (this.method.isAnnotationPresent(Loggable.class)) { |
| 421 |
this.level = this.method.getAnnotation(Loggable.class).value(); |
| 422 |
} else { |
| 423 |
this.level = Loggable.DEBUG; |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
/** |
| 428 |
* Get log level. |
| 429 |
* @return Log level of current method. |
| 430 |
*/ |
| 431 |
public final int getLevel() { |
| 432 |
return this.level; |
| 433 |
} |
| 434 |
|
| 435 |
@Override |
| 436 |
public final String toString() { |
| 437 |
return Mnemos.toText(this.method, this.arguments, true, false); |
| 438 |
} |
| 439 |
@Override |
| 440 |
public final int hashCode() { |
| 441 |
return this.method.hashCode(); |
| 442 |
} |
| 443 |
@Override |
| 444 |
public final boolean equals(final Object obj) { |
| 445 |
final boolean equals; |
| 446 |
if (this == obj) { |
| 447 |
equals = true; |
| 448 |
} else if (obj instanceof MethodCacher.Key) { |
| 449 |
final MethodCacher.Key key = MethodCacher.Key.class.cast(obj); |
| 450 |
equals = key.method.equals(this.method) |
| 451 |
&& this.target.equals(key.target) |
| 452 |
&& Arrays.deepEquals(key.arguments, this.arguments); |
| 453 |
} else { |
| 454 |
equals = false; |
| 455 |
} |
| 456 |
return equals; |
| 457 |
} |
| 458 |
/** |
| 459 |
* Send a result through, with necessary logging. |
| 460 |
* @param result The result to send through |
| 461 |
* @return The same result/object |
| 462 |
* @checkstyle DesignForExtensionCheck (2 lines) |
| 463 |
*/ |
| 464 |
public Object through(final Object result) { |
| 465 |
final int hit = this.accessed.getAndIncrement(); |
| 466 |
final Class<?> type = this.method.getDeclaringClass(); |
| 467 |
if (hit > 0 && LogHelper.enabled(this.level, type)) { |
| 468 |
LogHelper.log( |
| 469 |
this.level, |
| 470 |
type, |
| 471 |
"%s: %s from cache (hit #%d, %[ms]s old)", |
| 472 |
this, |
| 473 |
Mnemos.toText(result, true, false), |
| 474 |
hit, |
| 475 |
System.currentTimeMillis() - this.start |
| 476 |
); |
| 477 |
} |
| 478 |
return result; |
| 479 |
} |
| 480 |
/** |
| 481 |
* Is it related to the same target? |
| 482 |
* @param point Proceeding point |
| 483 |
* @return True if the target is the same |
| 484 |
*/ |
| 485 |
public final boolean sameTarget(final JoinPoint point) { |
| 486 |
return MethodCacher.Key.targetize(point).equals(this.target); |
| 487 |
} |
| 488 |
/** |
| 489 |
* Calculate its target. |
| 490 |
* @param point Proceeding point |
| 491 |
* @return The target |
| 492 |
*/ |
| 493 |
private static Object targetize(final JoinPoint point) { |
| 494 |
final Object tgt; |
| 495 |
final Method method = MethodSignature.class |
| 496 |
.cast(point.getSignature()).getMethod(); |
| 497 |
if (Modifier.isStatic(method.getModifiers())) { |
| 498 |
tgt = method.getDeclaringClass(); |
| 499 |
} else { |
| 500 |
tgt = point.getTarget(); |
| 501 |
} |
| 502 |
return tgt; |
| 503 |
} |
| 504 |
|
| 505 |
} |
| 506 |
} |