01: /*
02: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tcclient.cache;
05:
06: public class CacheInvalidationTimer {
07:
08: private final long delayInSecs;
09: private final String timerName;
10: private EvictionRunner runner;
11:
12: public CacheInvalidationTimer(final long delayInSecs,
13: final String timerName) {
14:
15: this .delayInSecs = delayInSecs;
16: this .timerName = timerName;
17: }
18:
19: public void start(CacheEntryInvalidator evictor) {
20: if (delayInSecs <= 0) {
21: return;
22: }
23:
24: this .runner = new EvictionRunner(delayInSecs, evictor);
25: Thread t = new Thread(runner, timerName);
26: t.setDaemon(true);
27: t.start();
28: }
29:
30: public void stop() {
31: if (runner != null) {
32: runner.cancel();
33: }
34: }
35:
36: private static class EvictionRunner implements Runnable {
37: private final long delayMillis;
38: private volatile boolean running = true;
39: private final transient CacheEntryInvalidator evictor;
40:
41: public EvictionRunner(final long delayInSecs,
42: final CacheEntryInvalidator evictor) {
43: this .evictor = evictor;
44: this .delayMillis = delayInSecs * 1000;
45: }
46:
47: public void cancel() {
48: running = false;
49: }
50:
51: public void run() {
52: long nextDelay = delayMillis;
53: try {
54: do {
55: sleep(nextDelay);
56: evictor.run();
57: } while (running);
58: } finally {
59: evictor.postRun();
60: }
61: }
62:
63: private void sleep(long l) {
64: try {
65: Thread.sleep(l);
66: } catch (InterruptedException ignore) {
67: // nothing to do
68: }
69: }
70:
71: }
72: }
|