All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.intelie.pipes.util.ObjectPool Maven / Gradle / Ivy

There is a newer version: 0.25.5
Show newest version
package net.intelie.pipes.util;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;

public class ObjectPool {
    private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();
    private final Supplier factory;
    private final int maxRetries;

    @SuppressWarnings({"unused", "FieldCanBeLocal"})
    private final List strong;
    //keeping a strong reference to minPoolSize elements to avoid their collection

    public ObjectPool(Supplier factory) {
        this(factory, 1, 5);
    }

    public ObjectPool(Supplier factory, int minPoolSize, int maxRetries) {
        this.maxRetries = maxRetries;
        this.factory = factory;
        this.strong = initMinPool(factory, minPoolSize);
    }

    private List initMinPool(Supplier factory, int minPoolSize) {
        List strong = new ArrayList<>();
        for (int i = 0; i < minPoolSize; i++) {
            try (Ref ref = new Ref(factory.get())) {
                strong.add(ref.obj());
            }
        }
        return strong;
    }

    public Ref acquire() {
        Ref ref = null;

        for (int i = 0; i < maxRetries; i++) {
            ref = queue.poll();

            //either empty pool or valid deref'd object
            if (ref == null || ref.materialize()) break;

            ref = null;
        }

        if (ref == null)
            ref = new Ref(factory.get());

        return ref;
    }

    public class Ref implements SafeCloseable {
        private final SoftReference ref;
        private T obj;

        private Ref(T obj) {
            this.ref = new SoftReference<>(obj);
            this.obj = obj;
        }

        private boolean materialize() {
            this.obj = ref.get();
            return this.obj != null;
        }

        public T obj() {
            return obj;
        }

        @Override
        public void close() {
            if (obj == null) return;
            obj = null;
            queue.offer(this);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy