Created
December 23, 2011 09:53
-
-
Save reikje/1513758 to your computer and use it in GitHub Desktop.
Using reference maps for caches and listeners 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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