Object Pooling in Java

后端 未结 7 1703
鱼传尺愫
鱼传尺愫 2020-12-29 08:19

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 exc

7条回答
  •  独厮守ぢ
    2020-12-29 08:23

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

    Benefits:

    • Fewer objects created - if object creation is expensive, this can be significant. (The canonical example is probably database connections, where "creation" includes making a network connection to the server, providing authentication etc.)

    Downsides:

    • More complicated code
    • Shared resource = locking; potential bottleneck
    • Violates GC's expectations of object lifetimes (most objects will be shortlived)

    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.

提交回复
热议问题