如何创建一个对象池以能够借用和归还对象

发布于 2024-12-27 22:46:29 字数 58 浏览 5 评论 0原文

我想知道,是否可以创建一个对象池?这样我就可以从池中取出一个对象,一旦完成工作,我就可以将其放入池中。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

魂归处 2025-01-03 22:46:29

我想知道是否可以创建对象池?这样我就可以从池中取出一个对象,一旦完成工作,我就可以将其放入池中。

有可能是的。如果新对象的构建成本高昂(例如建立数据库连接)或者由于其他原因 GC 带宽太高(在 Android 领域通常是一个问题),您可以在许多情况下看到性能改进。

以下是一些可用于实施池的资源。您也许可以立即使用 Apache 的 ObjectPool

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.

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.

去了角落 2025-01-03 22:46:29

虽然已经晚了但可能有用。

以下链接提供了使用 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

鯉魚旗 2025-01-03 22:46:29

作为替代方案,如果每个对象的重量不是那么重,并且/或者您不介意为每个线程保留该对象,请考虑 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文