
jdplus.toolkit.desktop.plugin.util.Pools Maven / Gradle / Ivy
/*
* Copyright 2013 National Bank of Belgium
*
* Licensed under the EUPL, Version 1.1 or – as soon they will be approved
* by the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package jdplus.toolkit.desktop.plugin.util;
import java.lang.reflect.InvocationTargetException;
import java.util.Deque;
import java.util.LinkedList;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
*
* @author Philippe Charles
*/
public final class Pools {
private Pools() {
// static class
}
@NonNull
public static Pool on(@NonNull Class extends X> clazz, int maxPoolSize) {
return on(new BasicFactory<>(clazz), maxPoolSize);
}
@NonNull
public static Pool on(Pool.@NonNull Factory factory, int maxPoolSize) {
return new BasicPool<>(factory, maxPoolSize);
}
static class BasicPool implements Pool {
final Factory factory;
final int maxPoolSize;
final Deque data;
int wildCount;
BasicPool(@NonNull Factory factory, int maxPoolSize) {
this.factory = factory;
this.maxPoolSize = maxPoolSize;
this.data = new LinkedList<>();
wildCount = 0;
}
@Override
public T getOrCreate() {
wildCount++;
T result = data.pollLast();
return result != null ? result : factory.create();
}
@Override
public void recycle(T o) {
if (data.size() < maxPoolSize) {
factory.reset(o);
data.offerLast(o);
} else {
factory.destroy(o);
}
wildCount--;
}
@Override
public void clear() {
for (T o : data) {
factory.destroy(o);
}
data.clear();
}
}
static class BasicFactory implements Pool.Factory {
final Class extends T> clazz;
BasicFactory(@NonNull Class extends T> clazz) {
this.clazz = clazz;
}
@Override
public T create() {
try {
return clazz.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void reset(T o) {
// do nothing
}
@Override
public void destroy(T o) {
// do nothing
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy