In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
本篇内容介绍了"如何使用Object-Pool对象池"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
Object-Pool 对象池
对于一个实例化比较困难的对象, 我们可以使用原型模式克隆一个对象, 这种方法是在创建的角度节约资源
另外一种节约资源的方法就是使用Object-Pool对象池模式, 它能将有限多个对象缓存起来,达到资源重复使用的目的,像我们常用的数据库连接池,其实就是保存了连接对象的 对象池.
public class SqlConnection { private Integer connectionId; public SqlConnection() { Random random = new Random(System.currentTimeMillis()); this.connectionId = random.nextInt(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }}
模拟SqlConnection创建时间需要很久的情况
public abstract class ObjectPool { private final Set canUse = new HashSet(); private final Set inUse = new HashSet(); protected abstract T create(); public synchronized T getOut() { if (canUse.isEmpty()) { canUse.add(create()); } var instance = canUse.iterator().next(); canUse.remove(instance); inUse.add(instance); return instance; } public synchronized void putIn(T instance) { inUse.remove(instance); canUse.add(instance); } @Override public synchronized String toString() { return String.format("可用=%d 使用中=%d", canUse.size(), inUse.size()); }}public class SqlConnectionPool extends ObjectPool{ @Override protected SqlConnection create() { return new SqlConnection(); }}public static void main(String[] args) { SqlConnectionPool sqlConnectionPool = new SqlConnectionPool(); System.out.println(sqlConnectionPool.toString()); var connection1 = sqlConnectionPool.getOut(); System.out.println(sqlConnectionPool.toString()); var connection2 = sqlConnectionPool.getOut(); var connection3 = sqlConnectionPool.getOut(); System.out.println(sqlConnectionPool.toString()); sqlConnectionPool.putIn(connection1); sqlConnectionPool.putIn(connection2); System.out.println(sqlConnectionPool.toString()); var connection4 = sqlConnectionPool.getOut(); var connection5 = sqlConnectionPool.getOut(); System.out.println(sqlConnectionPool.toString()); }"如何使用Object-Pool对象池"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.