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

【Jmeter】报错解决:JedisException: Could not return the broken resource to the pool Redis 连接无法正常释放导致报错: redis.clients.jedis.exceptions.JedisException: Could not return the broken resource to the pool Caused by: java.lang.IllegalStateException: Invalidated object not currently part of this pool 阅读详情

本人摘自:http://sourcemaking.com/design_patterns/object_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.


  • 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).


Check list

  1. Create ObjectPool class with private array of Objects inside
  2. Create acquare and release methods in ObjectPool class
  3. 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<T> {
  private long expirationTime;

  private Hashtable<T, Long> locked, unlocked;

  public ObjectPool() {
    expirationTime = 30000; // 30 seconds
    locked = new Hashtable<T, Long>();
    unlocked = new Hashtable<T, Long>();
  }

  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<T> 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<Connection> {

  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);
 
  }
}

多数据资源池 Zones are logical groupings of Nova Services and VM Hosts. Not all Zones need to contain Hosts; they may also contain other Zones to permit more manageable organizational structures. Our vision for Zones also allows for multiple root nodes (top-level Zones) so business units can partition the hosts in different ways for different purposes (i.e. geographical zones vs. functional zones). This proposal will outline our understanding of the issues surrounding Multi-Cluster and discuss some implementation ideas. 立即下载

相关推荐

一种资源池的实现

博客配套文件,详细演示了一种通用资源池的实现,给出了测试代码。

对象池原理 php,Object Pool Design Pattern in PHP 对象池设计模式在PHP中应用举例

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 ...

weixin_34847632的博客 204

数据中心架构资源池改造方案.pdf

数据中心架构资源池改造方案.pdf数据中心架构资源池改造方案.pdf数据中心架构资源池改造方案.pdf数据中心架构资源池改造方案.pdf数据中心架构资源池改造方案.pdf数据中心架构资源池改造方案.pdf

openGauss高级特性:资源池化

资源池化特性主要提供主备机共享一份存储的能力,提供一种新HA部署形态,解决传统HA部署下存储容量较单机翻倍的问题,满足降低存储容量及成本的诉求,同时备机支持实时一致性读。资源池化整体架构图如下所示。图 1资源池化架构图磁阵设备并且已经安装ultrapath多路径软件,磁阵设备可用。分布式存储服务DSS(Distributed Storage Service)DSS组件分为DSSAPI和DSSSERVER。DSSSERVER是独立进程,直接管理磁阵裸设备,并对外提供类似分布式文件系统的能力;

weixin_53596073的博客 2052

解决nfs挂载根文件系统报错:VFS: Unable to mount root fs via NFS, trying floppy.

解决nfs挂载根文件系统报错的问题:VFS: Unable to mount root fs via NFS, trying floppy.

汉尼拔勇闯天涯 4579

ORB-SLAM3单目+IMU实战:从数据加载到位姿优化的完整流程解析

本文详细解析了ORB-SLAM3单目+IMU模式的完整实战流程。从EuRoC等数据集的数据格式准备、系统启动与数据流入口,到帧构建、IMU预积分、视觉-惯性联合初始化,再到基于运动模型的跟踪、局部地图优化及多线程协同,提供了从环境配置到代码解读的全面指南,并分享了参数调优与性能分析的实用调试经验。

weixin_29085151的博客 298

sql server数据库资源池连接池爆满处理

超时时间已到,但是尚未从池中获取链接。

weixin_51803498的博客 2540

树莓派34/100 - Pico读取MPU6050加速度和陀螺仪传感器数据

树莓派Pico连接MPU-6050模块(三轴陀螺仪+三轴加速度),读取运动姿态数据。

申龙斌的程序人生 5092

Sql Server缓冲池、连接池等基本知识(附Demo)

缓存机制是指将经常访问的数据或查询结果保存在内存中,以提高查询性能和整体系统响应速度

码农研究僧的博客 1949

全网首发:香橙派5MAX安装ubuntu20.04(换了官方桌面)及ros,运行LIVOX-mid360混合固态激光雷达,实际测试fastlio(只能说可以跑,还是有点吃力)

独家发布!!!香橙派5MAX安装ubuntu20.04(换了官方桌面)及ros,运行mid360混合固态激光雷达,测试fastlio(只能说可以跑,还是有点吃力),国货也算崛起了。

2402_82745259的博客 6001

手把手教你在全新服务器内网安装OpenEuler 22.03 LTS SP4+ 安装 openGuass 5.0.0(LTS) 数据库

openEuler是面向数字基础设施的操作系统,支持服务器、云计算、边缘计算、嵌入式等应用场景,支持多样性计算,致力于提供安全、稳定、易用的开源服务器Linux操作系统。

cgqyw的专栏 3740

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

翻译到了一半,感觉还是看原味的比较好点,翻译过的东西和原味的怎么都是有差别。有人想看的话我给贴出来。Object PoolDesign PatternIntentObject pooling can offer a significant performance boost; it is most effective in situations where the cost of initial...

weixin_35867979的博客 668

Docker新手必看:解决‘Unable to find image’错误的完整指南

本文针对Docker新手常见的‘Unable to find image’错误,提供了完整的排查与解决指南。文章深入剖析了权限不足、网络连接失败、Docker服务未运行等核心原因,并给出了将用户加入docker组、配置镜像加速器等实用解决方案,帮助读者彻底理解并解决镜像拉取问题。

weixin_29230901的博客 245

设计模式沉思录:一 资源池

文章首发链接:https://mp.weixin.qq.com/s/pUjm_u6xaoFreK_36qITcg 公众号:程序员架构进阶 一 摘要 在工作中,经常会看到或者用到池化技术,例如数据库连接池、线程池、内存池等等。这类池化技术在很多经典框架中都存在,并且是设计中的重要部分。本篇将分析几种常见的池化技术框架,并结合业务案例来做资源池设计探索。 二 资源 2.1 什么是资源? 资源,百度上的解释是生产资料或生活资料的天然来源。在生活中可能这样描述没有问题,但似乎无法更准确地圈定...

程序员架构进阶 1365

嵌入式系统开发笔记96:将STM32CubeIDE设置为中文

本文介绍将STM32CubeIDE设置为中文的方法。

snmplink的博客 8540

联邦学习中的差分隐私保护详解及python实现

随着数据隐私法规(如 GDPR、CCPA)日益严格,传统将数据集中到云端训练模型的方式面临合规与安全风险。联邦学习通过让各客户端保留本地数据,仅共享模型更新,缓解了数据流动带来的隐私风险。但模型更新仍可能泄露个体信息。为进一步保障隐私,可在本地更新中引入差分隐私(DP)机制,通过向梯度或模型更新中注入随机噪声,防止反向推断原始数据citeturn0search9。

闲人编程的博客 1923

关于数据访问模式(八)—— Resource Pool模式

        Resource Pool(资源池)模式已经在上一篇Post中露过脸了,这次让我们再对其看个仔细吧。Resource Pool模式是在应用程序开发中十分常见的一种模式,如果你使用过任何一个主流的应用服务器,如Tomcat,Weblogic,Websphere,Resin等等,对连接池(Connection Pool)的配置一定都不会陌生。我们从几乎无处不在的连接池就可以知道Reso...

perhaps 454

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

什么是资源池技术?它有什么用?

更为重要的,我们详细分析了资源池的应用场景,并基于Mybatis这一主流ORM框架,给出了数据库连接池这一具体资源池的工作流程和实现过程。这里池(Pool)是一种对资源的抽象方法,代表一组可以随时使用的资源,但这些资源的创建和释放过程则基于一定的管理策略。接下来,为了模拟昂贵的对象初始化过程,我们可以构建如下所示的User类,注意到在构造函数中,我们通过Thread.sleep(1000)来模拟这种高成本的创建过程。资源池的概念本身比较简单,我们对它的基本操作进行抽象,可以自己实现一个资源池,如下所示。

2401_83062316的博客 3295

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

SQLServer 内存溢出问题?(待解决)

报错是在3个小时前的,但是问题还没有立即出现,3个小时左右,Windows系统操作总是出错,数据库连接不上。SQLserver代理总是自动停止,启动几分钟就停止。 部分错误如下:   --查看日志是否报内存信息 exec xp_readerrorlog 1,1,'Manager',NULL,'2015-01-23 13:00:00','20

1万+

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

重学设计模式 - Object Pool模式

1、意图 在创建对象比较昂贵,或者对于特定类型能够创建的对象数目有限制时,管理对象的重用。 2、问题 对象的创建和/或管理必须遵循一组定义明确的规则集。通常这些规则都与如何创建对象、能够创建多少个对象和在已有对象完成当前任务时如何重用它们等等相关。 3、通用结构 4、解决方案 在需要一个Reusable对象时,Client调用ReusablePool的A

在水一方 4610

设计模式之对象池模式(Object Pool)

http://blog.youkuaiyun.com/wcyoot/article/details/7584574 http://www.cnblogs.com/west-link/archive/2011/09/05/2167149.html 对象池模式 今天忽然看到一个有趣的设计模式,就上网看了下,现做一个整理。   前期了解:Object Pool,即对象池,对象被预先创建并初始化

yangqiang387393的博客 8891

对象池模式(Object Pool Pattern)。

定义 对象池模式,或者称为对象池服务,通过循环使用对象,减少资源在初始化和释放时的昂贵损耗。 注意:这里的“昂贵”可能是时间效益(如性能),也可能是空间效益(如并行处理),在大多的情况下,“昂贵”指性能。 简单的说,在需要时,从池中提取;不用时,放回池中,等待下一个请求。典型例子是连接池和线程池,这是我们开发中经常接触到的。 通用源码 对象池提供两个公共的方法:checkOut负责从池中...

孤芳不自赏 1103

设计模式(十一)Object Pool模式

Object Pool模式 使用Singleton模式构建对象池管理Manager,初始化N个对象,当需要使用时遍历N个对象,得到空闲对象,不使用时释放该对象。 Object Pool模式 关键特征 意图 在创建对象比较昂贵,或者对于特定类型能够创建的对象数目有限时,管理对象的重用。 问题 对象的创建和管理必须遵循一组定义明确的规则集。通常这些规则都与如何创建对象、能够创建多少...

xiaowei_innocence的博客 519
上一篇: Java Annotation自定义注解详解
下一篇: axis2 webservice 发布、调用与项目集成
七郎
博客等级 码龄14年 31粉丝 44原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值