Skip to content

Commit

Permalink
Using Supplier rather than Createror interface
Browse files Browse the repository at this point in the history
  • Loading branch information
belaban committed Oct 10, 2016
1 parent 12e7731 commit 922455a
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/org/jgroups/util/Pool.java
Expand Up @@ -4,25 +4,23 @@
import java.util.Map; import java.util.Map;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;


/** /**
* Manages a fixed pool of resources (e.g. buffers). Uses the fast try-lock operation to get a resource from the pool, * Manages a fixed pool of resources (e.g. buffers). Uses the fast try-lock operation to get a resource from the pool,
* or returns a newly created resource. When the returned lock is unlocks, that resource becomes available again * or returns a newly created resource. When the returned lock is unlocked, that resource becomes available again
* for consumption * for consumption
* @author Bela Ban * @author Bela Ban
* @since 3.5 * @since 3.5
*/ */
public class Pool<T> { public class Pool<T> {
protected final T[] pool; protected final T[] pool;
protected final Lock[] locks; protected final Lock[] locks;
protected final Creator<T> creator; protected final Supplier<T> creator;


public interface Creator<T> {
T create();
}


@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Pool(int capacity, Creator<T> creator) { public Pool(int capacity, Supplier<T> creator) {
this.creator=creator; this.creator=creator;
this.pool=(T[])new Object[Util.getNextHigherPowerOfTwo(capacity)]; this.pool=(T[])new Object[Util.getNextHigherPowerOfTwo(capacity)];
this.locks=new Lock[pool.length]; this.locks=new Lock[pool.length];
Expand Down Expand Up @@ -57,10 +55,10 @@ public Element<T> get() {
if(lock.tryLock()) { if(lock.tryLock()) {
if(pool[index] != null) if(pool[index] != null)
return new Element<>(pool[index], lock); return new Element<>(pool[index], lock);
return new Element<>(pool[index]=creator.create(), lock); return new Element<>(pool[index]=creator.get(), lock);
} }
} }
return new Element<>(creator.create(), null); return new Element<>(creator.get(), null);
} }




Expand All @@ -71,7 +69,7 @@ public String toString() {
return sb.toString(); return sb.toString();
} }


public class Element<T> { public static class Element<T> {
protected final T element; protected final T element;
protected final Lock lock; protected final Lock lock;


Expand Down

0 comments on commit 922455a

Please sign in to comment.