diff options
Diffstat (limited to 'yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java')
-rw-r--r-- | yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java b/yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java new file mode 100644 index 00000000000..5e7788e6e20 --- /dev/null +++ b/yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java @@ -0,0 +1,35 @@ +// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +package com.yahoo.yolean.concurrent; + +import com.yahoo.yolean.concurrent.ResourceFactory; + +import java.util.Iterator; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * @author baldersheim + */ +public class ConcurrentResourcePool<T> implements Iterable<T> { + + private final Queue<T> pool = new ConcurrentLinkedQueue<>(); + private final ResourceFactory<T> factory; + + public ConcurrentResourcePool(ResourceFactory<T> factory) { + this.factory = factory; + } + + public final T alloc() { + final T e = pool.poll(); + return e != null ? e : factory.create(); + } + + public final void free(T e) { + pool.offer(e); + } + + @Override + public Iterator<T> iterator() { + return pool.iterator(); + } +} |