blob: 6f5fb591ba64fc9f9c39d8498632fea223b4386a (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
// Copyright 2017 Yahoo Holdings. 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();
}
}
|