If you have many (hundreds) of requests per second, then implementing a connection pool is the way to go. See the answer to this for more details. However, if you are a Java newbie (we were all one day!), Then I donβt think you will need this requirement, and it will probably struggle to implement it.
Instead, a simple template for creating a new connection, if necessary, and then closing it upon completion will be the best way forward for you. Below is a modified version of your Database class, which I think is a good way forward.
class Database { private Connection con = null; private final String connectionString; public Database(String connectionString) { this.connectionString = connectionString; } public void connect() throws SQLException { if (con != null
Some points regarding this solution:
- This is not very effective - it takes longer to create a new connection than using an existing one.
- This class, if not thread safe - if you need this requirement, I recommend using a thread pool. However, if you create a new instance of this class for the stream, then it will be thread safe (since there is no static connection for concern!)
- This does the job - of course, for simple cases. I use a model for a relatively low volume database, which has about 50-100 connections made / closed per minute and does not add a noticeable delay.
- It is very reliable - nothing is safer than opening and closing a connection for each request. You are guaranteed to be able to handle connection failure for each request, and the connection will always be closed (if it was not already).
Disclaimer The decision above is not a particularly surprising solution. However, I find this easy to implement and a good way for a Java beginner to get to know the ropes before moving on to external libraries.
source share