/*
* Copyright 2008-2010 the T2 Project ant the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//package org.t2framework.commons.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
public class Pool {
private static int DEFAULT_POOL_MAX = 10;
private List stock;
private Set havings;
public static Pool create(T... stocks) {
return new Pool(Arrays.asList(stocks));
}
public static Pool create(T origin) {
return create(origin, DEFAULT_POOL_MAX);
}
public static Pool create(T origin, int poolMax) {
if (origin == null) {
throw new IllegalArgumentException("origin: " + origin);
}
if (poolMax < 1) {
throw new IllegalArgumentException("poolMax: " + poolMax);
}
List copies = new ArrayList();
for (int i = 0; i < poolMax; i++) {
try {
@SuppressWarnings("unchecked")
T copied = (T) origin.getClass().getMethod("clone").invoke(
origin);
copies.add(copied);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return new Pool(copies);
}
private Pool(List stocks) {
if (stocks == null || stocks.size() == 0) {
throw new IllegalArgumentException("stocks: " + stocks);
}
this.stock = new CopyOnWriteArrayList();
this.havings = new CopyOnWriteArraySet();
for (T stockItem : stocks) {
stock.add(stockItem);
havings.add(stockItem);
}
}
public T borrowItem() {
try {
while (true) {
if (0 < stock.size()) {
return stock.remove(0);
}
Thread.sleep(10);
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
public void returnItem(T item) {
if (havings.contains(item) == false) {
throw new IllegalStateException("item is not mine");
}
stock.add(item);
}
}