@Documented @Retention(value=RUNTIME) @Target(value=METHOD) public @interface Cacheable
For example, this load()
method loads some data from the network
and we want it to cache loaded data for 5 seconds (to avoid delays):
@Cacheable(lifetime = 5, unit = TimeUnit.SECONDS) String load(String resource) throws IOException { return "something"; }
You can cache them forever, which means that once calculated and cached value will never expire (may be a nice alternative to static initializers):
@Cacheable(forever = true) String load(String resource) throws IOException { return "something"; }
Since version 0.7.14 you can also annotate methods that should flush cache of the object.
Since 0.7.18 you can control when exactly flushing happens, with
Cacheable.FlushBefore
and Cacheable.FlushAfter
annotations
(Cacheable.Flush
is deprecated), for example:
public class Page { @Cacheable public String get() { // load data from external source, e.g. the network return data; } @Cacheable.FlushBefore public void set(String data) { // save data to the network } }
Modifier and Type | Optional Element and Description |
---|---|
Class<?>[] |
after
After-flushing trigger(s).
|
boolean |
asyncUpdate
Returns the current store after the expiration, and
then asynchronously update the data.
|
Class<?>[] |
before
Before-flushing trigger(s).
|
boolean |
forever
Keep in cache forever.
|
int |
lifetime
Lifetime of an object in cache, in time units.
|
TimeUnit |
unit
Time units of object lifetime.
|
public abstract int lifetime
public abstract TimeUnit unit
The minimum unit you can use is a second. We simply can't cache for less than a second, because cache is being cleaned every second.
public abstract boolean forever
public abstract boolean asyncUpdate
public abstract Class<?>[] before
Before calling the method, call static method flushBefore()
in this class and, according to its result, either flush or not.
For example:
class Foo { @Cacheable(before = Foo.class) int read() { // return some number } public static boolean flushBefore() { // if TRUE is returned, flushing will happen before // the call to #read() } }
public abstract Class<?>[] after
After calling the method, call static method flushAfter()
in this class and, according to its result, either flush or not.
For example:
class Foo { @Cacheable(after = Foo.class) int read() { // return some number } public static boolean flushAfter() { // if TRUE is returned, flushing will happen after // the call to #read() } }
Copyright © 2012–2017 jcabi.com. All rights reserved.