Concept:
Like frogs spawning, densely producing large quantities of eggs for future use
Objective:
Serves as an in-memory object pool with pre-allocation and pre-processing
Use Cases
Used in low-latency scenarios to replace allocation of numerous stateless small objects. Prevents latency fluctuations caused by GC.
Example: During interface serialization/deserialization
Managed objects need to implement a specific interface Resettable
public class DemoPojo implements Resettable {
...
}Need to implement a creator
public class DemoPojoCreator implements ObjectCreator<DemoPojo> {
@Override
public DemoPojo create() {
return new DemoPojo();
}
}Build object pool
PoolStrategy strategy = new PoolStrategy(
FetchStrategy.MUST_FETCH_IN_POOL, FetchFailStrategy.CALL_CREATOR, true);
ObjectsMemoryPool<DemoPojo> pool =
ObjectsMemoryPoolFactory.newPool(new DemoPojoCreator(), SIZE, strategy);Usage
try{
DemoPojo pojo = pojoPool.fetch();
// TODO using pojo
...
}finally{
pojoPool.release(pojo);
}Currently supports three different modes:
-
Must fetch from pool
PoolStrategy strategy = new PoolStrategy( FetchStrategy.MUST_FETCH_IN_POOL, FetchFailStrategy.CALL_CREATOR, true); ObjectsMemoryPool<DemoPojo> pool = ObjectsMemoryPoolFactory.newPool(new DemoPojoCreator(), SIZE, strategy);
-
Return null after certain fetch attempts
PoolStrategy strategy = new PoolStrategy( FetchStrategy.FETCH_FAIL_AS_NULL, FetchFailStrategy.CALL_CREATOR, true); ObjectsMemoryPool<DemoPojo> pojoPool = ObjectsMemoryPoolFactory.newPool(new DemoPojoCreator(), SIZE, strategy);
-
Create new object after certain fetch attempts
PoolStrategy strategy = new PoolStrategy( FetchStrategy.FETCH_FAIL_AS_NEW, FetchFailStrategy.CALL_CREATOR, true); ObjectsMemoryPool<DemoPojo> pojoPool = ObjectsMemoryPoolFactory.newPool(new DemoPojoCreator(), SIZE, strategy);
The last option is the default.
-Dfrogspawn.fetch.times: Maximum fetch attempts, default: 100-Dfrogspawn.max.capacity: Maximum pool capacity, default: 67108864 (65536*1024)-Dfrogspawn.cache.capacity: Thread cache capacity, default: 8, maximum: 64. Setting to1provides maximum performance.
The following content requires running on JDK8 specifically - no higher, no lower!!
@sun.misc.Contended Source Code
The annotation mentions it may be ineffective for subclasses. Therefore, current usage in the code might be ineffective.
Additional documentation states that the @Contended annotation requires JVM parameter -XX:-RestrictContended to be enabled.