1 45 package org.exolab.jms.lease; 46 47 48 import org.exolab.jms.service.BasicService; 49 import org.exolab.jms.service.ServiceException; 50 import org.exolab.jms.service.ServiceState; 51 import org.exolab.jms.common.util.OrderedQueue; 52 53 54 66 public class LeaseManager extends BasicService { 67 68 71 private static final String LEASE_MANAGER_THREAD_NAME = 72 "LeaseManagerReaper"; 73 74 77 private OrderedQueue _queue = null; 78 79 82 private static LeaseManager _instance = new LeaseManager(); 83 84 87 private final Object _waiter = new Object (); 88 89 90 94 protected LeaseManager() { 95 super(LEASE_MANAGER_THREAD_NAME); 96 _queue = new OrderedQueue(new LeaseComparator()); 97 } 98 99 104 public static LeaseManager instance() { 105 return _instance; 106 } 107 108 113 public void addLease(BaseLease lease) { 114 synchronized (_queue) { 115 _queue.add(lease); 116 if (_queue.firstElement() == lease) { 117 synchronized (_waiter) { 119 _waiter.notify(); 120 } 121 } 122 } 123 } 124 125 131 public boolean removeLease(BaseLease lease) { 132 boolean result = false; 133 134 synchronized (_queue) { 135 result = _queue.remove(lease); 136 } 137 if (result) { 138 synchronized (_waiter) { 139 _waiter.notify(); 140 } 141 } 142 143 return result; 144 } 145 146 152 public BaseLease renewLease(BaseLease lease, long duration) { 153 BaseLease newlease = null; 154 155 if ((lease != null) && (duration > 0)) { 156 synchronized (_queue) { 157 if (_queue.remove(lease)) { 159 lease.setDuration(duration); 160 _queue.add(lease); 161 newlease = lease; 162 synchronized (_waiter) { 163 _waiter.notify(); 164 } 165 } 166 } 167 } 168 169 return newlease; 170 } 171 172 175 public void removeAll() { 176 synchronized (_queue) { 177 _queue.clear(); 178 } 179 } 180 181 185 public void run() { 186 while (getState() != ServiceState.STOPPED) { 187 expire(); 188 189 synchronized (_waiter) { 191 try { 192 _waiter.wait(); 193 } catch (InterruptedException ignore) { 194 } 195 } 196 } 197 } 198 199 204 public void stop() throws ServiceException { 205 super.stop(); 206 synchronized (_waiter) { 207 _waiter.notifyAll(); 208 } 209 } 210 211 214 protected void expire() { 215 while (_queue.size() > 0) { 216 BaseLease lease = null; 217 boolean expired = false; 218 synchronized (_queue) { 219 lease = (BaseLease) _queue.firstElement(); 220 if (lease == null) { 221 continue; 222 } 223 224 if (lease.getExpiryTime() <= System.currentTimeMillis()) { 225 _queue.removeFirstElement(); 227 expired = true; 228 } 229 } 230 231 if (expired) { 232 lease.notifyLeaseExpired(); 233 } else { 234 long time = lease.getExpiryTime() - 237 System.currentTimeMillis(); 238 239 if (time > 0) { 240 try { 241 synchronized (_waiter) { 242 _waiter.wait(time); 243 } 244 } catch (InterruptedException ignore) { 245 } 246 } 247 } 248 } 249 } 250 251 } 252 | Popular Tags |