Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save reikje/1513758 to your computer and use it in GitHub Desktop.

Select an option

Save reikje/1513758 to your computer and use it in GitHub Desktop.
Using reference maps for caches and listeners 2
package javasplitter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.ExecutionException;
public class ExecutionTimingAuditableLifecycleListener implements AuditableLifecycleListener {
private final StatsCollector statsCollector;
private final LoadingCache<Auditable, Long> timedExecutionsCache =
CacheBuilder.newBuilder()
.weakKeys()
.build(
new CacheLoader<Auditable, Long>() {
@Override
public Long load(final Auditable key) throws Exception {
return System.currentTimeMillis();
}
}
);
public ExecutionTimingAuditableLifecycleListener(
final StatsCollector statsCollector) {
this.statsCollector = statsCollector;
}
@Override
public void onValidationStart(final Auditable auditable) {
try {
this.timedExecutionsCache.get(auditable);
} catch (ExecutionException e) {
// not thrown
}
}
@Override
public void onValidationFinish(final Auditable auditable) {
try {
this.statsCollector.collectValidationStats(
auditable.getClass(),
System.currentTimeMillis() - this.timedExecutionsCache.get(auditable)
);
} catch (ExecutionException e) {
// not thrown
} finally {
this.timedExecutionsCache.invalidate(auditable);
}
}
@Override
public void onProcessStart(final Auditable auditable) {
try {
this.timedExecutionsCache.get(auditable);
} catch (ExecutionException e) {
// not thrown
}
}
@Override
public void onProcessFinish(final Auditable auditable) {
try {
this.statsCollector.collectProcessStats(
auditable.getClass(),
System.currentTimeMillis() - this.timedExecutionsCache.get(auditable)
);
} catch (ExecutionException e) {
// not thrown
} finally {
this.timedExecutionsCache.invalidate(auditable);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment