import java.util.ArrayList;
import java.util.List;
public class ObjectUnit<T> {
private Class<T> type;
private List<T> items = new
ArrayList<T>();
private List<Boolean> checkedOut = new
ArrayList<Boolean>();
private int semaphore;
public ObjectUnit(Class<T>
type) {
this.type = type;
}
public synchronized T addItem() {
T obj;
try {
obj = type.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
items.add(obj);
checkedOut.add(false);
return obj;
}
public synchronized T checkOut() {
if (semaphore < items.size()) {
semaphore++;
return getItem();
} else
return addItem();
}
public synchronized void checkIn(T x) {
if (releaseItem(x))
semaphore--;
}
private synchronized T getItem() {
for (int index = 0; index < checkedOut.size();
index++)
if (!checkedOut.get(index)) {
checkedOut.set(index, true);
return items.get(index);
}
return null;
}
private synchronized boolean
releaseItem(T item) {
int index = items.indexOf(item);
if (index == -1)
return false; // Not in the list
if (checkedOut.get(index)) {
checkedOut.set(index, false);
return true;
}
return false;
}
}
|
import java.util.Map;
import
java.util.concurrent.ConcurrentHashMap;
public class Provider {
private Map<Class<?>,
ObjectUnit<?>> providers = new ConcurrentHashMap<Class<?>,
ObjectUnit<?>>();
private static Provider instance = new Provider();
private Provider() {
}
public static Provider getInstance() {
return instance;
}
@SuppressWarnings("unchecked")
public <T> T
getObj(Class<T> key) {
ObjectUnit value = providers.get(key);
if (value != null) {
return (T) value.checkOut();
} else {
value = new ObjectUnit<T>(key);
providers.put(key, value);
return (T) value.addItem();
}
}
@SuppressWarnings("unchecked")
public <T> void renObj(T x) {
if (providers.containsKey(x.getClass())) {
ObjectUnit value = providers.get(x.getClass());
value.checkIn(x);
}
}
}
|