Object pool
来源:互联网 发布:lapse it 编辑:程序博客网 时间:2024/06/06 21:43
package com.luoluo.recycle.n;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public abstract class Recycler<T>{ private final ThreadLocal<Stack<T>> threadLocal = new ThreadLocal<Stack<T>>() { @Override protected Stack<T> initialValue() { return new Stack<T>(); } }; public final T get() { Stack<T> stack = threadLocal.get(); T o = stack.pop(); if (o == null) { o = newObject(); } return o; } public final boolean recycle(T o) { Stack<T> stack = threadLocal.get(); stack.push(o); return true; } protected abstract T newObject(); private static final class Stack<T> { private T[] elements; private int size; @SuppressWarnings("unchecked") private Stack() { elements = (T[]) new Object[16]; } private T pop() { int size = this.size; if (size == 0) { return null; } size--; T o = this.elements[size]; this.elements[size] = null; this.size = size; return o; } private void push(T o) { int size = this.size; if ((size >= 256)) { return; } if (size == this.elements.length) { this.elements = Arrays.copyOf(this.elements, Math.min(size << 1, 256)); } this.elements[size] = o; this.size = size + 1; } } static Recycler<Student> recycler = new Recycler<Student>() { @Override protected Student newObject() { return new Student(); } }; public static void main(String[] args) { List<Student> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { list.add(recycler.get()); } for (Student student : list) { System.out.println(student); recycler.recycle(student); } System.out.println("--------------"); for (int i = 0; i < 5; i++) { list.add(recycler.get()); } for (Student student : list) { System.out.println(student); recycler.recycle(student); } }}class Student{ @Override public String toString() { return "Student-" + this.hashCode(); }}
0 0
- Object pool
- 对象池Object Pool
- Object Pool(C++11)
- Object Pool Design Pattern
- object pool【上】
- 深入浅出对象池(Object Pool)
- 深入浅出对象池(Object Pool)
- Lock Less Java Object Pool
- javascript Object Pool 对象池
- javascript Object Pool 对象池
- C#2.0 - Object Pool 简单实现
- 重学设计模式 - Object Pool模式
- Unity3D之对象池(Object Pool)
- 对象池(Object Pool)模式
- 使用apache commons pool时遇到IllegalStateException:returned object is not part of this pool
- Invalidated object not currently part of this pool/Could not return the resource to the pool
- Object源码, monitor (wait pool) , Thread.sleep(), interrupt
- Unity3D内存管理——对象池(Object Pool)
- 使用VS CODE+PlantUML高效画图
- MySql 启动与连接
- ElasticSearch学习资料
- 快速排序的实现
- maven配置完环境变量后无法识别mvn -v命令,或者重启后无法识别
- Object pool
- 题目1041:Simple Sorting
- 【编程】大鱼吃小鱼
- int类型数组转换成string数组
- 无锁队列的实现
- Python学习之字符串(二)
- Oracle 数据库表操作整理
- VC++下的OpenGL编程
- windows下安装mpi4py库