D
D
Dmitry Kamaev2015-12-16 14:14:26
Java
Dmitry Kamaev, 2015-12-16 14:14:26

What is the correct way to apply the Eviction Policy in org.apache.commons.pool2?

package com.mycompany.simplepool;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.EvictionConfig;
import org.apache.commons.pool2.impl.EvictionPolicy;

public class MyEvictionPolicy<T> implements EvictionPolicy<T> {
    
    @Override
    public boolean evict(EvictionConfig config, PooledObject<T> underTest, int idleCount) {
        System.out.println("MyEvictPolicy");
        if (Integer.parseInt(underTest.getObject().toString()) % 2 == 0) {
            System.out.println("Delete because % 2 == 0 ---- " + underTest.getObject());
            return true;
        }
        if ((config.getIdleSoftEvictTime() < underTest.getIdleTimeMillis() &&
                config.getMinIdle() < idleCount) ||
                config.getIdleEvictTime() < underTest.getIdleTimeMillis()) {
            return true;
        }
        return false;
    }
}

Implemented EvictionPolicy for String. I want to delete lines containing even numbers.
I create a pool:
BasePooledObjectFactory<String> poolFactory = new MyBasePooledObjectFactory();
GenericObjectPoolConfig configPool = new GenericObjectPoolConfig();
configPool.setTimeBetweenEvictionRunsMillis(10);
configPool.setMaxIdle(2);
GenericObjectPool<String> pool = new GenericObjectPool<>(poolFactory);
pool.setEvictionPolicyClassName(MyEvictionPolicy.class.getName()); // - задаю Eviction Policy
pool.setConfig(configPool);

However, the pool does not call my implementation of MyEvictionPolicy.evict when it checks for objects to remove. My implementation is only called when the pool.evict() method is explicitly called.
How can I make the pool use exactly my MyEvictionPolicy.evict during periodic checks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kamaev, 2015-12-16
@Kamaed

Poking around in the sources , I came to the conclusion that you can specify the EvictionPolicy in the config and pass it to the overloaded constructor.

BasePooledObjectFactory<String> poolFactory = new MyBasePooledObjectFactory();
GenericObjectPoolConfig configPool = new GenericObjectPoolConfig();
configPool.setTimeBetweenEvictionRunsMillis(100);
configPool.setMaxIdle(2);
configPool.setEvictionPolicyClassName(MyEvictionPolicy.class.getName());
GenericObjectPool<String> pool = new GenericObjectPool<>(poolFactory, configPool);

Then GenericObjectPool.evictionPolicy is set before the TimerTask starts with checks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question