    001    package org.maltparser.core.pool;
    002
    003
    004    import org.maltparser.core.exception.MaltChainedException;
    005    import org.maltparser.core.helper.HashSet;
    006
    007
    008    public abstract class ObjectPoolSet<T> extends ObjectPool<T> {
    009            private final HashSet<T> available;
    010            private final HashSet<T> inuse;
    011
    012            public ObjectPoolSet() {
    013                    this(Integer.MAX_VALUE);
    014            }
    015
    016            public ObjectPoolSet(int keepThreshold) {
    017                    super(keepThreshold);
    018                    available = new HashSet<T>();
    019                    inuse = new HashSet<T>();
    020            }
    021
    022            protected abstract T create() throws MaltChainedException;
    023            public abstract void resetObject(T o) throws MaltChainedException;
    024
    025            public synchronized T checkOut() throws MaltChainedException {
    026                    if (available.isEmpty()) {
    027                            T t = create();
    028                            inuse.add(t);
    029                            return t;
    030                    } else {
    031                            for (T t : available) {
    032                                    inuse.add(t);
    033                                    available.remove(t);
    034                                    return t;
    035                            }
    036                    }
    037                    return null;
    038            }
    039
    040            public synchronized void checkIn(T t) throws MaltChainedException {
    041                    resetObject(t);
    042                    inuse.remove(t);
    043                    if (available.size() < keepThreshold) {
    044                            available.add(t);
    045                    }
    046            }
    047
    048            public synchronized void checkInAll() throws MaltChainedException {
    049                    for (T t : inuse) {
    050                            resetObject(t);
    051                            if (available.size() < keepThreshold) {
    052                                    available.add(t);
    053                            }
    054                    }
    055                    inuse.clear();
    056            }
    057
    058            public String toString() {
    059                    final StringBuilder sb = new StringBuilder();
    060                    for (T t : inuse) {
    061                            sb.append(t);
    062                            sb.append(", ");
    063                    }
    064                    return sb.toString();
    065            }
    066    }