1 package org.apache.commons.jcs3.auxiliary;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.concurrent.locks.Condition;
24 import java.util.concurrent.locks.Lock;
25 import java.util.concurrent.locks.ReentrantLock;
26
27 import org.apache.commons.jcs3.log.Log;
28 import org.apache.commons.jcs3.log.LogManager;
29
30
31
32
33
34
35
36
37 public abstract class AbstractAuxiliaryCacheMonitor extends Thread
38 {
39
40 protected final Log log = LogManager.getLog( this.getClass() );
41
42
43 protected static long idlePeriod = 20 * 1000;
44
45
46
47
48 protected AtomicBoolean allright = new AtomicBoolean(true);
49
50
51
52
53 private final AtomicBoolean shutdown = new AtomicBoolean(false);
54
55
56 private final Lock lock = new ReentrantLock();
57
58
59 private final Condition trigger = lock.newCondition();
60
61
62
63
64
65
66 public AbstractAuxiliaryCacheMonitor(final String name)
67 {
68 super(name);
69 }
70
71
72
73
74
75
76 public static void setIdlePeriod( final long idlePeriod )
77 {
78 if ( idlePeriod > AbstractAuxiliaryCacheMonitor.idlePeriod )
79 {
80 AbstractAuxiliaryCacheMonitor.idlePeriod = idlePeriod;
81 }
82 }
83
84
85
86
87 public void notifyError()
88 {
89 if (allright.compareAndSet(true, false))
90 {
91 signalTrigger();
92 }
93 }
94
95
96
97
98 public void notifyShutdown()
99 {
100 if (shutdown.compareAndSet(false, true))
101 {
102 signalTrigger();
103 }
104 }
105
106
107 private void signalTrigger()
108 {
109 try
110 {
111 lock.lock();
112 trigger.signal();
113 }
114 finally
115 {
116 lock.unlock();
117 }
118 }
119
120
121
122
123 protected abstract void dispose();
124
125
126
127
128 protected abstract void doWork();
129
130
131
132
133 @Override
134 public void run()
135 {
136 do
137 {
138 if ( allright.get() )
139 {
140 log.debug( "ERROR DRIVEN MODE: allright = true, cache monitor will wait for an error." );
141 }
142 else
143 {
144 log.debug( "ERROR DRIVEN MODE: allright = false cache monitor running." );
145 }
146
147 if ( allright.get() )
148 {
149
150 try
151 {
152 lock.lock();
153 trigger.await();
154
155 }
156 catch ( final InterruptedException ignore )
157 {
158
159 }
160 finally
161 {
162 lock.unlock();
163 }
164 }
165
166
167 if ( shutdown.get() )
168 {
169 log.info( "Shutting down cache monitor" );
170 dispose();
171 return;
172 }
173
174
175
176 allright.set(true);
177
178 log.debug( "Cache monitor running." );
179
180 doWork();
181
182 try
183 {
184
185
186 log.debug( "Cache monitor sleeping for {0} between runs.", idlePeriod );
187
188 Thread.sleep( idlePeriod );
189 }
190 catch ( final InterruptedException ex )
191 {
192
193 }
194 }
195 while ( true );
196 }
197 }