Home  >  Article  >  Java  >  Java Object Pool: Usage and Examples

Java Object Pool: Usage and Examples

PHPz
PHPzforward
2023-04-25 20:49:061184browse

Instructions

1. Create a factory class and inherit or implement the basic interface.

By inheriting BaseGenericObjectPool or implementing the basic interface PooledObjectFactory, and rewriting the object creation, destruction, verification, activation, and passivation methods according to business needs, the destruction is mostly the closing and emptying of the connection.

2. Create a pool and inherit GenericObjectPool.

By inheriting GenericObjectPool or implementing the basic interface ObjectPool, it is recommended to use the former, which provides us with an idle object eviction detection mechanism (that is, destroying objects that have not been used for a long time in the idle queue to reduce memory usage), and provides A lot of basic information about objects, such as when the object was last used, whether to check before using the object, etc.

3. Create pool-related configurations

Increase the configuration control of the thread pool by inheriting GenericObjectPoolConfig or inheriting BaseObjectPoolConfig. It is recommended to use the former, which implements the basic methods for us. You only need to add it yourself. Just the required attributes.

4. Create a wrapper class

It is an object that needs to exist in the object pool, and many basic attributes are added to the actual object to facilitate understanding of the real-time status of the object in the object pool.

Example

private volatile int maxIdle = GenericObjectPoolConfig.DEFAULT_MAX_IDLE;
private volatile int minIdle = GenericObjectPoolConfig.DEFAULT_MIN_IDLE;
public static final int DEFAULT_MAX_IDLE = 8;
public static final int DEFAULT_MIN_IDLE = 0;

The above is the detailed content of Java Object Pool: Usage and Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete