Java中的对象池 [英] Object Pooling in Java

查看:127
本文介绍了Java中的对象池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

维护一个经常使用的对象池并从该池中获取一个而不创建一个新对象的优点和缺点是什么.类似于字符串实习,只是所有类对象都可以使用.

What are the pro's and con's of maintaining a pool of frequently used objects and grab one from the pool instead of creating a new one. Something like string interning except that it will be possible for all class objects.

例如,由于可以节省gc时间和对象创建时间,因此可以认为它是不错的选择.另一方面,如果从多个线程中使用它,则可能是一个同步瓶颈,需要进行显式释放,并可能导致内存泄漏.通过占用可以回收的内存,这对垃圾收集器施加了额外的压力.

For example it can be considered to be good since it saves gc time and object creation time. On the other hand it can be a synchronization bottleneck if used from multiple threads, demands explicit deallocation and introduces possibility of memory leaks. By tying up memory that could be reclaimed, it places additional pressure on the garbage collector.

推荐答案

除非创建对象昂贵,否则我不会打扰.

Unless the object is expensive to create, I wouldn't bother.

好处:

  • 创建的对象更少-如果创建对象很昂贵,那么这可能很重要. (典型示例可能是数据库连接,其中创建"包括与服务器建立网络连接,提供身份验证等.)

缺点:

  • 更复杂的代码
  • 共享资源=锁定;潜在的瓶颈
  • 违反了GC对对象寿命的期望(大多数对象将是短期的)

您是否有要解决的实际问题,还是这种推测?除非您的基准测试/配置文件运行表明存在问题,否则我不会考虑这样做.

Do you have an actual problem you're trying to solve, or is this speculative? I wouldn't think about doing something like this unless you've got benchmarks/profile runs showing that there's a problem.

这篇关于Java中的对象池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆