Mehran Mehran - 1 year ago 80
Java Question

Beans with time to live

For the long-lived beans, i.e. singleton and prototype, is there some way to specify a life span by the end of which Bean's

is called? In my opinion, the life span is defined as a period of time which the bean has been ideal and not used.

If there's no such thing, is there any way I can simulate this? Maybe some other library!


Consider the following scenario as a use case:

There are all kinds of pools out there for resources which might be frequently used in a period of time and then they would go out of style. One of the most well known such resources is a database connection.

For a software which might connect to multiple databases, there's an unpredictable demand for each connection over the time. In just cases, connection pools can help us not to close and re-establish database connection as this is an expensive process. And they do so by keeping the connection open for a while and if there's been a demand in that period, the connection's expiry date is reset.

This scenario can be applied to any resource which should be kept in memory only if there's a demand for it. Of course, once the resource is expired, it should be kicked out of memory. At this point, any new demand should respawn the resource before it is expired again.

Answer Source

Even though there's no such thing, but I came across another solution which solves this problem perfectly.

My solution is to define a singleton bean which returns a cache. The cache object provides you with the time-to-live functionality instead of the bean. Of course, if you need your cache to be per user, you can set your bean to be scoped to session instead of singleton.

I ended up using*.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download