1 23 package com.sun.enterprise.util; 24 25 import java.util.Hashtable ; 26 import java.util.Vector ; 27 28 import java.util.logging.*; 30 import com.sun.logging.*; 31 33 public abstract class ResourceCache 34 { 35 36 static Logger _logger=LogDomains.getLogger(LogDomains.UTIL_LOGGER); 38 40 43 public ResourceCache(int count) 44 { 45 resources = new Hashtable (); 46 this.count = count; 47 } 48 49 52 public Object getResource(Object name) throws Exception 53 { 54 Object resource = null; 55 Vector list = null; 56 Resource r = null; 57 58 synchronized (resources) { 60 61 list = (Vector ) resources.get(name); 62 63 if (list == null) { 64 list = new Vector (count); 65 resources.put(name, list); 66 } 67 } 68 69 boolean newR = false; synchronized (list) { 72 73 while (resource == null) { 74 75 for (int i=0; i < list.size(); i++) { 77 if ((r = (Resource) list.elementAt(i)).isAvailable()) { 78 r.markInUse(); 79 resource = r.getResource(); 80 break; 81 } 82 } 83 84 if (resource == null) { 86 if (list.size() < count) { 87 r = new Resource(); 88 list.addElement(r); 89 newR = true; 90 break; 91 } 92 93 if (!newR) list.wait(); 95 } 96 } 97 } 98 99 if (newR) { 101 102 try { 103 resource = createResource(name); 104 105 107 } catch (Exception ex) { 108 109 112 _logger.log(Level.SEVERE,"enterprise_util.excep_rescache_getres",ex); 114 } 116 117 synchronized (list) { 118 r.setResource(resource); 119 r.markInUse(); 120 } 121 } 122 123 return resource; 124 } 125 126 129 public void returnResource(Object name, Object oldResource, 130 Object newResource) 131 { 132 Resource r = null; 133 Vector list = (Vector ) resources.get(name); 134 135 if (list != null) { 136 synchronized (list) { 137 for (int i=0; i < list.size(); i++) { 138 r = (Resource) list.elementAt(i); 139 if (r.getResource() == oldResource) { 140 r.setResource(newResource); 141 r.markAvailable(); 142 list.notifyAll(); 143 break; 144 } 145 } 146 } 147 } 148 } 149 150 155 public abstract Object createResource(Object name) throws Exception ; 156 157 private Hashtable resources; 158 private int count; 159 } 160 161 164 class Resource 165 { 166 private static final int IN_USE=1; 167 private static final int AVAILABLE=2; 168 private static final int NOT_AVAILABLE=3; 169 170 private Object resource; 171 private int state; 172 173 176 Resource() 177 { 178 resource = null; 179 state = NOT_AVAILABLE; 180 } 181 182 185 Object getResource() 186 { 187 return resource; 188 } 189 190 193 void setResource(Object resource) 194 { 195 this.resource = resource; 196 } 197 198 201 void markAvailable() 202 { 203 state = AVAILABLE; 204 } 205 206 209 void markInUse() 210 { 211 state = IN_USE; 212 } 213 214 217 boolean isAvailable() 218 { 219 return (state == AVAILABLE) ? true : false; 220 } 221 } 222 | Popular Tags |