summaryrefslogtreecommitdiffstats
path: root/yolean/src/main/java/com/yahoo/yolean/concurrent/ResourcePool.java
blob: 62d5d749604432da57052dc8ebbcc3439b38f310 (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
36
37
38
// 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.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

/**
 * <p>This implements a simple stack based resource pool. If you are out of resources new are allocated from the
 * factory.</p>
 *
 * @author baldersheim
 * @since 5.2
 */
public final class ResourcePool<T> implements Iterable<T> {

    private final Deque<T> pool = new ArrayDeque<>();
    private final ResourceFactory<T> factory;

    public ResourcePool(ResourceFactory<T> factory) {
        this.factory = factory;
    }

    public final T alloc() {
        return pool.isEmpty() ? factory.create() : pool.pop();
    }

    public final void free(T e) {
        pool.push(e);
    }

    @Override
    public Iterator<T> iterator() {
        return pool.iterator();
    }
}