aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java
blob: 0e91a44bf5d401b87416b1d0d76cbca12411774b (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.yolean.concurrent;

import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;

/**
 * A pool of a resource. This create new instances of the resource on request until enough are created
 * to deliver a unique one to all threads needing one concurrently and then reuse those instances
 * in subsequent requests.
 *
 * @author baldersheim
 */
public class ConcurrentResourcePool<T> implements Iterable<T> {

    private final Queue<T> pool = new ConcurrentLinkedQueue<>();
    private final Supplier<T> factory;


    public ConcurrentResourcePool(Supplier<T> factory) {
        this.factory = factory;
    }

    public void preallocate(int instances) {
        for (int i = 0; i < instances; i++) {
            pool.offer(factory.get());
        }
    }

    /**
     * Allocates an instance of the resource to the requestor.
     * The resource will be allocated exclusively to the requestor until it calls free(instance).
     *
     * @return a reused or newly created instance of the resource
     */
    public final T alloc() {
        T e = pool.poll();
        return e != null ? e : factory.get();
    }

    /** Frees an instance previously acquired bty alloc */
    public final void free(T e) {
        pool.offer(e);
    }

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

}