Skip to content

Commit

Permalink
SoftReference for cached result
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikolay Nesterov committed Mar 11, 2016
1 parent 19b0e0e commit 0b911ac
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/main/java/com/jcabi/aspects/aj/MethodCacher.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.jcabi.aspects.Cacheable;
import com.jcabi.aspects.Loggable;
import com.jcabi.log.Logger;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
Expand Down Expand Up @@ -260,7 +261,7 @@ protected static final class Tunnel {
/**
* Cached value.
*/
private transient Object cached;
private transient SoftReference<Object> cached;

/**
* Public ctor.
Expand All @@ -277,7 +278,7 @@ protected static final class Tunnel {

@Override
public String toString() {
return Mnemos.toText(this.cached, true, false);
return Mnemos.toText(this.cached.get(), true, false);
}

/**
Expand All @@ -299,7 +300,7 @@ public Tunnel copy() {
public synchronized Object through() throws Throwable {
if (!this.executed) {
final long start = System.currentTimeMillis();
this.cached = this.point.proceed();
this.cached = new SoftReference<Object>(this.point.proceed());
final Method method = MethodSignature.class
.cast(this.point.getSignature())
.getMethod();
Expand Down Expand Up @@ -327,21 +328,23 @@ public synchronized Object through() throws Throwable {
Mnemos.toText(
method, this.point.getArgs(), true, false
),
Mnemos.toText(this.cached, true, false),
Mnemos.toText(this.cached.get(), true, false),
System.currentTimeMillis() - start,
suffix
);
}
this.executed = true;
}
return this.key.through(this.cached);
return this.key.through(this.cached.get());
}
/**
* Is it expired already?
* @return TRUE if expired
*/
public boolean expired() {
return this.executed && this.lifetime < System.currentTimeMillis();
final boolean expired = this.lifetime < System.currentTimeMillis();
final boolean collected = cached.get() == null;
return this.executed && (expired || collected);
}

/**
Expand Down

0 comments on commit 0b911ac

Please sign in to comment.