01: package dalma.impl;
02:
03: import dalma.Executor;
04: import dalma.helpers.ThreadPoolExecutor;
05:
06: /**
07: * Base class that provides regular reloading logic.
08: *
09: * @author Kohsuke Kawaguchi
10: */
11: public abstract class Reloadable {
12: private static final Executor reloader = new ThreadPoolExecutor(1,
13: true);
14:
15: private long nextReloadTime;
16: private boolean updateInProgress;
17:
18: /**
19: * True if the data is loaded at least once.
20: */
21: private boolean initialDataFetched = false;
22:
23: private final Runnable task = new Runnable() {
24: public void run() {
25: try {
26: initialDataFetched = true;
27: reload();
28: } finally {
29: setNextReloadTime();
30: }
31: }
32: };
33:
34: protected Reloadable() {
35: setNextReloadTime();
36: }
37:
38: private void setNextReloadTime() {
39: this .nextReloadTime = System.currentTimeMillis() + 5000;
40: }
41:
42: public void update() {
43: if (!initialDataFetched) {
44: // if no data has loaded before, fetch it now synchronously
45: synchronized (this ) {
46: if (!initialDataFetched) {
47: initialDataFetched = true;
48: task.run();
49: return;
50: }
51: }
52: }
53: if (System.currentTimeMillis() > nextReloadTime
54: && !updateInProgress) {
55: updateInProgress = true;
56: reloader.execute(task);
57: }
58: }
59:
60: public abstract void reload();
61: }
|