当前位置: 首页 > news >正文

java 简易的资源池_资源池设计模式 (Resource Pool)和数据池的简单实现

翻译到了一半,感觉还是看原味的比较好点,翻译过的东西和原味的怎么都是有差别。有人想看的话我给贴出来。

Object Pool Design Pattern

Intent

Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

Problem

Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.

It is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, the Reusable Pool class is designed to be a singleton class.

Discussion

The Object Pool lets others "check out" objects from its pool, when those objects are no longer needed by their processes, they are returned to the pool in order to be reused.

However, we don't want a process to have to wait for a particular object to be released, so the Object Pool also instantiates new objects as they are required, but must also implement a facility to clean up unused objects periodically.

Structure

The general idea for the Connection Pool pattern is that if instances of a class can be reused, you avoid creating instances of the class by reusing them.

fd241c3f129cf01b4a4ef89771ea0f08.png

Reusable - Instances of classes in this role collaborate with other objects for a limited amount of time, then they are no longer needed for that collaboration.

Client - Instances of classes in this role use Reusable objects.

ReusablePool - Instances of classes in this role manage Reusable objects for use by Client objects.

Usually, it is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, theReusablePool class is designed to be a singleton class. Its constructor(s) are private, which forces other classes to call its getInstance method to get the one instance of the ReusablePoolclass.

A Client object calls a ReusablePool object's acquireReusable method when it needs aReusable object. A ReusablePool object maintains a collection of Reusable objects. It uses the collection of Reusable objects to contain a pool of Reusable objects that are not currently in use.

If there are any Reusable objects in the pool when the acquireReusable method is called, it removes a Reusable object from the pool and returns it. If the pool is empty, then theacquireReusable method creates a Reusable object if it can. If the acquireReusable method cannot create a new Reusable object, then it waits until a Reusable object is returned to the collection.

Client objects pass a Reusable object to a ReusablePool object's releaseReusable method when they are finished with the object. The releaseReusable method returns a Reusableobject to the pool of Reusable objects that are not in use.

In many applications of the Object Pool pattern, there are reasons for limiting the total number of Reusable objects that may exist. In such cases, the ReusablePool object that creates Reusable objects is responsible for not creating more than a specified maximum number of Reusable objects. If ReusablePool objects are responsible for limiting the number of objects they will create, then the ReusablePool class will have a method for specifying the maximum number of objects to be created. That method is indicated in the above diagram as setMaxPoolSize.

Example

Do you like bowling? If you do, you probably know that you should change your shoes when you getting the bowling club. Shoe shelf is wonderful example of Object Pool. Once you want to play, you'll get your pair (aquireReusable) from it. After the game, you'll return shoes back to the shelf (releaseReusable).

82f9f969ffa45461af7bc0f5b6850ea8.png

Check list

Create ObjectPool class with private array of Objects inside

Create acquare and release methods in ObjectPool class

Make sure that your ObjectPool is Singleton

Rules of thumb

The Factory Method pattern can be used to encapsulate the creation logic for objects. However, it does not manage them after their creation, the object pool pattern keeps track of the objects it creates.

Object Pools are usually implemented as Singletons.

====================

下面是详细实现代码,在代码里并没有对设置数据池的最大最小数量、客户端数进行设置,代码的意图在于通过设计一个简单的数据池来表达资源池的概念:

// ObjectPool Class

public abstract class ObjectPool {

private long expirationTime;

private Hashtable locked, unlocked;

public ObjectPool() {

expirationTime = 30000; // 30 seconds

locked = new Hashtable();

unlocked = new Hashtable();

}

protected abstract T create();

public abstract boolean validate(T o);

public abstract void expire(T o);

public synchronized T checkOut() {

long now = System.currentTimeMillis();

T t;

if (unlocked.size() > 0) {

Enumeration e = unlocked.keys();

while (e.hasMoreElements()) {

t = e.nextElement();

if ((now - unlocked.get(t)) > expirationTime) {

// object has expired

unlocked.remove(t);

expire(t);

t = null;

} else {

if (validate(t)) {

unlocked.remove(t);

locked.put(t, now);

return (t);

} else {

// object failed validation

unlocked.remove(t);

expire(t);

t = null;

}

}

}

}

// no objects available, create a new one

t = create();

locked.put(t, now);

return (t);

}

public synchronized void checkIn(T t) {

locked.remove(t);

unlocked.put(t, System.currentTimeMillis());

}

}

//The three remaining methods are abstract

//and therefore must be implemented by the subclass

public class JDBCConnectionPool extends ObjectPool {

private String dsn, usr, pwd;

public JDBCConnectionPool(String driver, String dsn, String usr, String pwd) {

super();

try {

Class.forName(driver).newInstance();

} catch (Exception e) {

e.printStackTrace();

}

this.dsn = dsn;

this.usr = usr;

this.pwd = pwd;

}

@Override

protected Connection create() {

try {

return (DriverManager.getConnection(dsn, usr, pwd));

} catch (SQLException e) {

e.printStackTrace();

return (null);

}

}

@Override

public void expire(Connection o) {

try {

((Connection) o).close();

} catch (SQLException e) {

e.printStackTrace();

}

}

@Override

public boolean validate(Connection o) {

try {

return (!((Connection) o).isClosed());

} catch (SQLException e) {

e.printStackTrace();

return (false);

}

}

}

JDBCConnectionPool will allow the application to borrow and return database connections:

public class Main {

public static void main(String args[]) {

// Do something...

...

// Create the ConnectionPool:

JDBCConnectionPool pool = new JDBCConnectionPool(

"org.hsqldb.jdbcDriver", "jdbc:hsqldb://localhost/mydb",

"sa", "secret");

// Get a connection:

Connection con = pool.checkOut();

// Use the connection

...

// Return the connection:

pool.checkIn(con);

}

}

相关文章:

  • java替代重定向_Java 重定向与管道
  • java五子棋聊天功能_Java基于享元模式实现五子棋游戏功能实例详解
  • bandpass filter java_带通滤波器设计(Bandpass filter design).doc
  • java的位桶是什么,hashmap中的存储桶究竟是什么?
  • 缴费java代码_基于jsp的物业管理缴费系统-JavaEE实现物业管理缴费系统 - java项目源码...
  • java实体类间的转换_java 实体类集合转换和实体类转换
  • mysql碎片整理 提速_MysqL碎片整理优化
  • 一张纸对折13次JAVA_一张纸最多折叠8次?她把纸折叠了13次后,发生了什么?
  • plsq卸载 删除注册表、_oracle安装及使用常见问题及解决方案
  • 陈伟伟java_java开发学习笔记之图书管理系统
  • java的list集合详解_【java集合】List详解
  • java bean 命名_fastjson(javabean命名)
  • php按钮控制css命令,php实现的CSS更新类实例
  • sigbus php,php-fpm里常用参数优化解析
  • php表单提交防注入,php表单提交数据的验证处理(防SQL注入和XSS攻击等)
  • 【剑指offer】让抽象问题具体化
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • Angular 4.x 动态创建组件
  • avalon2.2的VM生成过程
  • GitUp, 你不可错过的秀外慧中的git工具
  • mac修复ab及siege安装
  • Odoo domain写法及运用
  • overflow: hidden IE7无效
  • Python语法速览与机器学习开发环境搭建
  • seaborn 安装成功 + ImportError: DLL load failed: 找不到指定的模块 问题解决
  • 对象引论
  • 力扣(LeetCode)22
  • 聊聊springcloud的EurekaClientAutoConfiguration
  • 盘点那些不知名却常用的 Git 操作
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 微信开源mars源码分析1—上层samples分析
  • LIGO、Virgo第三轮探测告捷,同时探测到一对黑洞合并产生的引力波事件 ...
  • ​2020 年大前端技术趋势解读
  • ​queue --- 一个同步的队列类​
  • ​卜东波研究员:高观点下的少儿计算思维
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • #Z0458. 树的中心2
  • (3)nginx 配置(nginx.conf)
  • (C#)Windows Shell 外壳编程系列9 - QueryInfo 扩展提示
  • (Mirage系列之二)VMware Horizon Mirage的经典用户用例及真实案例分析
  • (免费分享)基于springboot,vue疗养中心管理系统
  • (转)mysql使用Navicat 导出和导入数据库
  • ***监测系统的构建(chkrootkit )
  • .md即markdown文件的基本常用编写语法
  • .NET 4 并行(多核)“.NET研究”编程系列之二 从Task开始
  • .NET 设计模式—简单工厂(Simple Factory Pattern)
  • .NET使用HttpClient以multipart/form-data形式post上传文件及其相关参数
  • .php结尾的域名,【php】php正则截取url中域名后的内容
  • [\u4e00-\u9fa5] //匹配中文字符
  • [17]JAVAEE-HTTP协议
  • [AndroidStudio]_[初级]_[修改虚拟设备镜像文件的存放位置]
  • [BZOJ 3680]吊打XXX(模拟退火)
  • [COGS 622] [NOIP2011] 玛雅游戏 模拟
  • [c语言]小课堂 day2
  • [Electron]ipcMain.on和ipcMain.handle的区别