如何创建一个对象池以能够借用和归还对象
我想知道,是否可以创建一个对象池?这样我就可以从池中取出一个对象,一旦完成工作,我就可以将其放入池中。
I wanted to know that, is it possible to create a pool of objects? So that I can take an object from the pool and once I'm done with the work, I can put it into the pool.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有可能是的。如果新对象的构建成本高昂(例如建立数据库连接)或者由于其他原因 GC 带宽太高(在 Android 领域通常是一个问题),您可以在许多情况下看到性能改进。
以下是一些可用于实施池的资源。您也许可以立即使用 Apache 的
ObjectPool
。It is possible yes. You can see performance improvements in many situations if the construction of a new object is expensive (like establishing a database connection) or if for other reasons the GC bandwidth is too high (often a problem in Android-land).
Here are some resources that you could use to implement your pool. You may be able to use Apache's
ObjectPool
right out of the box.虽然已经晚了但可能有用。
以下链接提供了使用 apache-commons-pool-2 创建对象池的足够信息和实现细节:
https://dzone.com/articles/creating-object-pool-java
Though its late but might be useful.
Following link provides sufficient information and implementation details for creating object pool using apache-commons-pool-2:
https://dzone.com/articles/creating-object-pool-java
作为替代方案,如果每个对象的重量不是那么重,并且/或者您不介意为每个线程保留该对象,请考虑 ThreadLocal 对象。
http://tutorials.jenkov.com/java-concurrency/threadlocal.html
As an alternative, if each object isn't that heavy weight, and/or you don't mind keeping the object around for each thread, consider ThreadLocal objects.
http://tutorials.jenkov.com/java-concurrency/threadlocal.html