Beans with time to live - java

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 destroyMethod 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!
[UPDATE]
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.

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 com.google.common.cache.*.

Related

Timeout mechanism with changeable usage time

I want to implement mechanism which will be closing connections if there are not used by specific period of time. This time is constant for all of the connections. Opened connections can be used many times, so I need to update usage time and always compute difference between current time and usage time. I also need to close connections which excess my timeout.
My opened connections are in Map. (Map<Id, Connection>) where Id is an Integer.
I thought about resolving my problem with DelayQueue, but there is no possible to update usage (in this case delay) time in this type of Queue.
I also know that this mechanism should work in separate thread.
Please, give me some tip about the best way of implementation or example. What kind of data structure should I use?
I can use Spring also (maybe there is some good mechanism and I don't know about it).
If you're speaking about database connectivity then just use connection poolers such as c3po, hikariCP, BoneCP and so on. Don't reinvent the wheel.
Take a look at the HikariCP code. Specifically, look at:
ConcurrentBag
PoolBagEntry
BaseDataSource.getConnection()
BaseDataSource.releaseConnection()
HouseKeeper inner class
While HikariCP is a database connection pool, you can use ConcurrentBag as is, use the HouseKeeper basically as is, slightly modify PoolBagEntry, and lift the basic gist from getConnection() and releaseConnection(), to create a generic pool.

How to properly handle long-lived MySQL connections in Java when using Guice Injections?

I hate stating questions that apparently seem to have a lot of solutions online, but we really cannot seem to find any valid best-practice solution for our case, and therefore felt we had no choice.
We are building an RESTful server application in which the periods between use may differ from a couple of hours to multiple months.
The server is hosted by Jetty. We are not using any ORM, but the application is layered into three layers (WebService- , Business- and Data Layer). The Data layer exist of one class injected through the Guice framework. The JDBC (MySQL connection) is instantiated within the constructor of this class. At first, we had a lot of trouble with too many connections before we understood that Guice by default creates a new instance on each request(ref). To get rid of this problem, and because our Data layer class is stateful, we made the class injected as Singleton.
Now we've foreseen that we might run into trouble when our REST application is not used for some time, since the connection will time out, and no new connection will be instantiated, as the constructor will only be called once.
We now have multiple solutions, but we cannot seem to figure out the best way to solve this, as none of them really seems to be that good. Any input or suggestions to other solutions would be well appreciated.
1. Extend the configured mysql timeout interval
We really do not want this, as we think it's really not best practice. We should of course not have any leaking connection objects, but if we have, they would fill up the free space of connections available.
2. Instantiate a new connection at the beginning of each method, and close it at the end
This is, as far as we understand, not best practice at all, as it would cause a lot of overhead, and should be avoided if possible?
3. Change the injections back to "per-request", and close the pool at the end of each method
This would be even worse than #2, as we would not only instantiate a new connection, but also instantiate a new object on each request?
4. Check the status of the connection at the beginning of each method, and instantiate a new connection if it's closed
An example would be to ping (example) the mysql, and instantiate a new connection if it throws an exceptions. This would work, but it would create some overhead. Any ideas of whether this input actually would make any difference to the performance?
5. Explicitly catch any exceptions being thrown in the methods indicating that the connection is down, and if so - instantiate a new connection
This way, we would get rid of the ping overhead, but it would complicate our code remarkably, as we would have to figure out a way to make sure that the methods will return what they would have returned if the connection where already alive.
6. Use a connection pool
We are not familiar with connection pools, other than when using an application server (i.e Glassfish). We're also wondering whether this actually would solve our problem? And if so; any suggestions on any framework providing us with connection pools? Here they suggest using PLUS with Jetty.
Please ask if there's anything unclear. I might have forgotten to add some vital information. This is to me more of a design question, but I'd be glad to provide any code if anyone thinks that would help.
Thanks in advance!
Connection pools are the way to go.
They have a number of advantages:
They check your connections for you - this deals with timeouts
They control the number of connections
You can simply close the connection when your done - you don't need to keep references
You should certainly keep connections in some sort of pool, and in fact you will almost certainly end up writing one yourself eventually if you don't bite the bullet.
By the time you have implemented connection checking so that they don't go stale, some sort of connection holder so that you don't need to re-open them each time, some sort of exception handling code...you get my drift.
I have used dbcp and boneCP and both are very easy to use and configure and will save you hours and hours of frustration dealing with JDBC connection issues.
I am not overly familiar with Guice but I assume it has some way to provide your own factory method for Object, so you can use that to get connections from your pool and then simple call close() when you're done to return them to the pool.
If you're using a webserver you can always use an interceptor or filter to bind connections to the work thread and discard them after processing in which case your connection provider would only need to yank the one tied to the current thread.
Inject a Provider<Connection> instead and have the provider give out connections (EDIT: at the time you need it) from a connection pool which can detect stale entries.
Unreturned connections should be discarded from the pool.

Why database connection object or connection pool needs to be made singleton?

I have gone through couple of articles on singleton example. And I could see that developers sometimes make the database connection object or connection manager as singleton implementation. In some of the posts even it was advised to use Database connection pool.
Well Singleton means to create a single instance, so basically we restrict the access. e.g. Printer or hardware access, logger access in which we try to restrict the access of the user to one at a time using singleton. However what is the purpose of using singleton in DB connection objects?
If I can understand correctly creating a Database connection as singleton means that app server will have only one instance. Does this mean only one user can access the Database connection and next user has to wait until the connection is closed?
Please advise.
I think you understand correctly the implication of making the connection itself a singleton. Generally it is not a good idea (although in some very particular case it could make sense).
Making a connection manager or a connection pool a singleton is completely different. The pool itself would handle a collection of connections and it can create new as they are needed (up to a limit) or re-use the ones that have been already used and discarded.
Having several connection pools at the same time would lose the advantages of the pool:
It would be harder to control the total number of connections open
One pool could be creating connections while other could have connections available
Hope this helps to clarify the subject. You might want to read more on connection pools.
Q: "However what is the purpose of using singleton in DB connection objects?" A: There is (almost always) none. So your thinking is correct.
Q: "Does this mean only one user can access the Database connection and next user has to wait until the connection is closed?"
A: Depends (to first part) and No (to second part after "and"). In single-threaded application only one user will use the database at one time and another will wait, until dispatch of first user ends but not when the connection is closed. Once connection is closed, you need to create another connection to make use of database. In multi-threaded application many threads may be using the same connection instance and result really depends on the vendor implementation: may block dispatching (effectively transforming your app to single-threaded app) or throw exceptions or even something different. However, such design in multi-threaded app is in my opinion a programmer-error.

How singleton is used to manage database connection?

This may be a very old, many times asked question. But I am not able to find a proper answer to it, so asking again.
For the database connections, we always use a singleton object. When the database is being accessed by thousands of users, how does the performance is maintained? I mean if there are thousands of requests per second, how the database connection is managed since we are using a singleton? Are the database requests serialized? Or a singleton is not used in these cases?
I know it is a kind of dumb question, but I am seriously confused. If anyone can give some reference reading link, it will be nice.
Thanks.
I'm not sure whether you've confused the use of a plain singleton with a service locator. Both of them are design patterns. The service locator pattern is used by applications to ensure that there is a single class entrusted with the responsibility of obtaining and providing access to databases, files, JMS queues, etc.
Most service locators are implemented as singletons, since there is no need for multiple service locators to do the same job. Besides, it is useful to cache information obtained from the first lookup that can be later used by other clients of the service locator.
By the way, the argument about
"it's to ensure that there is always only one active connection to your DB"
is false and misleading. It is quite possible that the connection can be closed/reclaimed if left inactive for quite a long period of time. So caching a connection to the database is frowned upon. There is one deviation from this argument; "re-using" the connection obtained from the connection pool is encouraged as long as you do so with the same context, i.e. within the same HTTP request, or user request (whichever is applicable). This done obviously, from the point of view of performance, since establishing new connections can prove to be an expensive operation.
i recommend to use connection poolinghttp://www.java2s.com/Code/Java/Database-SQL-JDBC/PooledConnectionExample.htm
Even though you haven't put anything about sessions/transactions/ORM, I think your question comes from Hibernate, JPA or other ORM background.
As such, for any transaction to happen, we need an entityManager or session. These sessions could be created for each transaction.
Now by using factory pattern, we can get as many similar objects as we want... But the factory itself should be singleton. So in DB operations, the entityManagerFactory or sessionFactory objects are kept as singletons.
When you think about it, it makes sense because after all a sessionFactory represents a configuration(DB, UserID, password, connection pool size, caching, etc). What you need to perform DB transaction is not the factory but the object(session) created by the factory. These you can have as many as you want. But if you have multiple factories, it just is unnecessary creation of same (similar) objects.
We use connection pooling in plain jdbc as well as ORM.
If your database connection creating singleton is stateless (which it should be, or at least should be immutable), its pretty simple.
When your web application is accessed by thousands of users simultaneously, there are actually thousands of threads, one per user. Each thread has its own Program Counter which keeps track of what instruction thread is currently processing. When a thread would access a public method of your singleton, for example myDBConnectionManager.getConnection(), it would start executing instructions specified within. Therefore, it is a thread that is actually creating a database connection by reading instructions specified in myDBConnectionManager.getConnection() method. The methods of singleton are only manuals that instruct threads what to do.
This way, your application can create millions of connections at the same time with a singleton as long as it is able to create millions of threads simultaneously.

Should JDBC connection handles be per-app, per-thread, or per-query?

Let's say we've got a web application or web service on an application server supporting JDBC connection pooling.
Should I be grabbing a new Connection on a per-thread or per-query basis?
Thanks!
Hopefully you are grabbing them on a per-transactional-unit-of-work basis.
Per query implies that you never have any logical unit of work in your system that spans more than a single query. (Maybe that's true, but you still might want to think about the future!)
Per-thread (which I assume to mean request-scoped, rather than for the entire life of the thread?) will probably result in holding them for longer than absolutely necessary, but it does allow you to manage transactions much better. (and it's how plenty of leading frameworks have worked or did work for a long time. A pattern known as Open Entity Manager In View, if you'd like to do some google-fu on it)
Assigning it indefinitely to a single thread means your max number of active request processors is capped at the max size of your database pool, which is a definite failure in scalability.
per-thread
Each new request will grab a new connection (new thread = new request). There is no need for getting a new connection for each query as after each query the connection can be reused.

Categories

Resources