1 24 25 package org.objectweb.dream.pool; 26 27 import org.objectweb.dream.AbstractComponent; 28 import org.objectweb.dream.util.EmptyStringArray; 29 import org.objectweb.dream.util.Error; 30 import org.objectweb.util.monolog.api.BasicLevel; 31 32 39 public class ObjectPoolImpl extends AbstractComponent 40 implements 41 ObjectPool, 42 ObjectPoolAttributeController 43 { 44 45 private Recyclable pool[]; 46 47 48 private int elementCount = 0; 49 50 51 private int capacity; 52 53 54 private String className = null; 55 56 57 private Class objectClass; 58 59 private final Object lock = new Object (); 60 61 65 68 public Recyclable newInstance() 69 { 70 Recyclable obj = null; 71 synchronized (lock) 72 { 73 if (elementCount == 0) 74 { 75 if (logger.isLoggable(BasicLevel.DEBUG)) 76 { 77 logger.log(BasicLevel.DEBUG, "Creates new instance of class " 78 + className); 79 } 80 try 81 { 82 obj = (Recyclable) objectClass.newInstance(); 83 } 84 catch (Exception e) 85 { 86 Error.bug(logger, e); 89 } 90 } 91 else 92 { 93 elementCount -= 1; 94 obj = pool[elementCount]; 95 pool[elementCount] = null; 96 } 97 } 98 return obj; 99 } 100 101 104 public void recycleInstance(Recyclable recyclable) 105 { 106 if (recyclable != null && objectClass.isInstance(recyclable)) 107 { 108 recyclable.recycle(); 109 synchronized (lock) 110 { 111 if (elementCount == pool.length) 112 { 113 if (logger.isLoggable(BasicLevel.WARN)) 114 { 115 logger.log(BasicLevel.WARN, "Pool Full"); 116 } 117 return; 118 } 119 pool[elementCount] = recyclable; 120 elementCount += 1; 121 } 122 } 123 } 124 125 129 132 public int getCapacity() 133 { 134 return capacity; 135 } 136 137 140 public void setCapacity(int capacity) 141 { 142 synchronized (lock) 144 { 145 this.capacity = capacity; 146 pool = new Recyclable[capacity]; 147 elementCount = 0; 148 } 149 } 150 151 154 public String getObjectClassName() 155 { 156 return className; 157 } 158 159 162 public void setObjectClassName(String name) 163 { 164 if (className != null) 165 { 166 logger.log(BasicLevel.ERROR, 167 "This object pool already manages objects of class " + className); 168 new IllegalArgumentException ( 169 "This object pool already manages objects of class " + className); 170 } 171 this.className = name; 172 try 173 { 174 objectClass = Class.forName(name); 175 Recyclable r = (Recyclable) objectClass.newInstance(); 177 } 178 catch (Exception e) 179 { 180 logger.log(BasicLevel.ERROR, "Invalid class " + className, e); 181 new IllegalArgumentException ("Invalid class " + className); 182 } 183 } 184 185 191 public String [] listFc() 192 { 193 return EmptyStringArray.EMPTY_STRING_ARRAY; 194 } 195 196 } | Popular Tags |