пятница, 19 сентября 2014 г.

When to use Object pool pattern?

Various pools - Thread pools, connection pools, EJB object pools - Flyweight is really about management of shared resources


You need to frequently create and destroy objects.

Objects are similar in size.

Allocating objects on the heap is slow or could lead to memory fragmentation.

Each object encapsulates a resource such as a database or network connection that is expensive to acquire and could be reused.

Basically, we'll use an object pool whenever there are several clients who needs the same stateless resource which is expensive to create.

When there are several clients who need the same resource at different times.

It is deprecated as a general technique, because - as you noticed - creation and destruction of short lived objects per se (i.e. memory allocation and GC) is extremely cheap in modern JVMs. So using a hand-written object pool for your run-of-the-mill objects is most likely slower, more complicated and more error-prone than plain new.*

It still has its uses though, for special objects whose creation is relatively costly, like DB / network connections, threads etc.

Комментариев нет:

Отправить комментарий