What is the best way in Java to create a singleton?
Should a DB connection be a singleton (being a singleton it's automatically thread-safe)? Because theoretical the DB can't be accessed by many users in the same time.
A DB connection should not normally be a Singleton.
Two reasons:
many DB drivers are not thread safe. Using a singleton means that if you have many threads, they will all share the same connection. The singleton pattern does not give you thread saftey. It merely allows many threads to easily share a "global" instance.
Personally, I think Singleton often leads to bad design: See this post (by somebody else) http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/
Instead of doing this consider a database pool. The pool is shared (and could be a singleton if you wanted). When you need to do database work your code does this:
getConnectioFromPool();
doWork()
closeConnection() // releases back to pool
Sample Pool Libraries:
http://commons.apache.org/dbcp/
http://jolbox.com/
The best way to create a singleton (as of today) is the enum singleton pattern (Java enum singleton)
I doubt, that a Singleton is necessary or of any value for a database connection. You probably want some lazy creation: a connection is created upon first demand and cached, further requests will be fullfilled with the cached instance:
public ConnectionProvider {
private Connection conn;
public static Connection getConnection() {
if (conn == null || conn.isClosed()) {
conn = magicallyCreateNewConnection();
}
return conn;
}
}
(not thread safe - synchronize, if needed)
What is the best way in Java to create
a singleton?
Follow the design pattern creation guidelines. i.e private constructor, etc.
Should a DB connection be a singleton
(being a singleton it's automatically
thread-safe)?
creating a DB connection as a singleton might be a poor design choice in many scenarios. Use it only if you are sure that you don't need DB concurrency. If you have multiple users logged in at the same time, or even if your single user spawns many threads that need to access the DB, then a DB Connection pool is a better choice. You can use either apache or tomcat db connection pools. THese classes are defined for example in the package
org.apache.commons.dbcp.*;
org.apache.tomcat.dbcp.dbcp.*;
where dbcp stands for database connection pooling.
The biggest reason for using a connection pool is that on average the time it takes for the DB access (DML etc) is much smaller than the time it takes to create a connection and then close the connection. Additionally, don't forget to close your ResultSet, PreparedStatement and Connection variables after the transaction is done.
Because theoretical the DB can't be
accessed by many users in the same
time.
Why not? DB in most cases is meant to be used concurrently. You have these DB isolation levels - READ_COMMITTED, READ_UNCOMMITTED, SERIALIZED etc.
SERIALIZED is the case where your DB becomes single user access.
Singletons are a pattern - there's no explicit way to create one, you just follow the design practice.
So, if you're using a database that can handle concurrent reads/writes (i.e. MySQL), you don't need to worry so much about thread safety. If you're using a DB that's doesn't do concurrent writes well (SQLite), then a singleton should theoretically work.
Related
I am really getting confused between these 2 now as below :
1. is the returning of only a Singleton instance to a db connection during the entire run time of a JAVA app
2. is the concept of Thread pool connections in general... I mean if we are planning to have only a singleton instance to a db connection obj, why even have a concept of pools, though i do get what exactly a pool is used for
Are these 2 not very opposite concepts, or am i mixing up anything here...?
is the returning of only a Singleton instance to a db connection during the entire run time of a JAVA app?
you may not want to return a Singleton object for a database connection. You can choose to do if database concurrency not required. In a multi threaded environment best option is to go for Connection pool.
is the concept of Thread pool connections in general..
Establishing a database connection is a very resource-intensive process and involves a lot of overhead. Moreover, in a multi-threaded environment, opening and closing a connection can worsen the situation greatly.
Creating JNDI in server and use it in your web app.
Context context=new InitialContext();
DataSource dataSource=(DataSource)
context.lookup("jdbc/test_jndi");
so when DataSource uses connection pooling, the lookup return a connection from the pool of available connection objects. If there is no available connection, the lookup creates a new connection.
Connection connection=dataSource.getConnection
("testuser","testpwd");
// ...
connection.close();
Once the application is done with database processing, it explicitly closes the connection. This makes the connection available again for reuse again. The closing event of the pooled connection signals the pooling module to restore back to the connection pool.
Any resource shared requires overhead of handling concurrent access so you want to reduce that by not having singletons always. Moreover to reduce resource-intensive process connection pooling is preferred.
I have a severe problem with my database connection in my web application. Since I use a single database connection for the whole application from singleton Database class, if i try concurrent db operations (two users) the database rollsback the transactions.
This is my static method used:
All threads/servlets call static Database.doSomething(...) methods, which in turn call the the below method.
private static /* synchronized*/ Connection getConnection(final boolean autoCommit) throws SQLException {
if (con == null) {
con = new MyRegistrationBean().getConnection();
}
con.setAutoCommit(true); //TODO
return con;
}
What's the recommended way to manage this db connection/s I have, so that I don't incurr in the same problem.
Keeping a Connection open forever is a very bad idea. It doesn't have an endless lifetime, your application may crash whenever the DB times out the connection and closes it. Best practice is to acquire and close Connection, Statement and ResultSet in the shortest possible scope to avoid resource leaks and potential application crashes caused by the leaks and timeouts.
Since connecting the DB is an expensive task, you should consider using a connection pool to improve connecting performance. A decent applicationserver/servletcontainer usually already provides a connection pool feature in flavor of a JNDI DataSource. Consult its documentation for details how to create it. In case of for example Tomcat you can find it here.
Even when using a connection pool, you still have to write proper JDBC code: acquire and close all the resources in the shortest possible scope. The connection pool will on its turn worry about actually closing the connection or just releasing it back to pool for further reuse.
You may get some more insights out of this article how to do the JDBC basics the proper way. As a completely different alternative, learn EJB and JPA. It will abstract away all the JDBC boilerplate for you into oneliners.
Hope this helps.
See also:
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
Am I Using JDBC Connection Pooling?
How should I connect to JDBC database / datasource in a servlet based application?
When is it necessary or convenient to use Spring or EJB3 or all of them together?
I've not much experience with PostgreSql, but all the web applications I've worked on have used a single connection per set of actions on a page, closing it and disposing it when finished.
This allows the server to pool connections and stops problems such as the one that you are experiencing.
Singleton should be the JNDI pool connection itself; Database class with getConnection(), query methods et al should NOT be singleton, but can be static if you prefer.
In this way the pool exists indefinitely, available to all users, while query blocks use dataSource.getConnection() to draw a connection from the pool; exec the query, and then close statement, result set, and connection (to return it to the pool).
Also, JNDI lookup is quite expensive, so it makes sense to use a singleton in this case.
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.
Every time we implement a PooledConnection we write
class MyConnection implements PooledConnection, Connection {
// implement methods of PooledConnection and Connection
}
And I am wondering why PooledConnection was not designed as extends Connection? since a PooledConnection is always a Connection after all.
I'm by no means sure, but I imagine the reason PooledConnection doesn't extend Connection is so that you can make a significantly simpler PooledConnection implementation that uses any other existing Connection implementation, allowing code-reuse and keeping functionality separate.
... since a PooledConnection is always a Connection after all.
Actually, that's the whole point. The PooledConnection interface design allows the PooledConnection instance to be a distinct object from the Connection instance.
Why would you do that? Well in an XA implementation, there are potentially many different implementations of Connection from different database vendors, and the PooledConnection classes are designed to deal with "stuff" over the top of that; e.g. coordination of transactions across multiple databases. Keeping the two interfaces distinct means that the XA implementation doesn't need to implement XA-level connections as wrapper objects.
And of course, since PooledConnection and Connection interfaces, they can be implemented by the same connection class ... if the situation requires it.
(Or at least, that is my theory. To get a definitive answer, you'd need to ask the people who wrote the specification(s) that gave rise to those interfaces.)
A PooledConnection is a handle to a physical connection. This physical connection object might be a a JDBC Connection, but on the other hand it could just as well be a lower-level database-specific construct.
The handle is what a connection pool uses to create logical Connection-objects to hand out to clients of the connection pool (using the getConnection() method. When the client closes that connection, the connection pool is notified that the PooledConnection is available again.
A PooledConnection is not intended to be used directly as a Connection, so it does not extend the Connection interface.
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.