3

I'm writing a servlet that handles each request by accessing and modifying some table(s) in the database. I want the connections to the database to be thread safe. I don't want to use already existing libraries/frameworks for this (spring, hibernate, etc.).

I know I can use java's ThreadLocal for this in the following way :

public class DatabaseRegistry { //assume it's a singleton


    private Properties prop = new Properties();
    
    public static final ThreadLocal<Connection> threadConnection = new ThreadLocal<Connection>();
    
    private Connection connect() throws SQLException {
        try {
            // This will load the MySQL driver, each DB has its own driver
            Class.forName("com.mysql.jdbc.Driver");
            // Setup the connection with the DB
            Connection connection = DriverManager
                    .getConnection("jdbc:mysql://" + prop.getProperty("hostname") + "/" + prop.getProperty("database") + "?"
                            + "user=" + prop.getProperty("username") + "&password=" + prop.getProperty("password"));
            return connection;
        } catch (SQLException e) {          
            throw e;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } 
        
        return null;
        
    }
    
    public Connection getConnection() throws SQLException {
        
        if (threadConnection.get() == null) {
            Connection connection = connect();
            threadConnection.set(connection);
            return threadConnection.get();
        } else {
            return threadConnection.get();
        }
    } 

    private void freeConnection(Connection connection) throws SQLException {
        connection.close();
        threadConnection.remove();
    }
}

Each time you call getConnection(), the new connection is added to the ThreadLocal object and then removed when you free the connection.

Is this the proper way of doing this or should the DatabaseRegistry itself extend the ThreadLocal<Connection> class? Or is there an even better way to do this to make all connections thread safe?

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    http://stackoverflow.com/questions/1209693/is-mysql-connector-jdbc-thread-safe – Peter Cetinski Feb 25 '12 at 16:11
  • I think it is not a good practice. please use connection pool, it will be remain core size of available connections. If you use ThreadLocal, every request will be own one connect, if your web Server is block, the connect won't be release ontime. – zg_spring Mar 20 '15 at 02:26

3 Answers3

4

I don't think that making database connections thread-safe is a common practice. Usually what you want is either:

  • Serialize the access to some part of your servlet, so that there is no more than one servlet executing code at a time (e.g. implementing the SingleThreadModel interface).
  • Locking a particular table / table page / row so you can operate on some particular tuple (by changing the database isolation level).
  • Using optimistic locking to detect modified rows in a table (using some reference attribute of the table to check if the current version is the same that the one in the table).

AFAIK, the typical use of ThreadLocal<Connection> is to store a unique database connection per thread, so that the same connection can be used in different methods in your business logic without the need of passing it as a parameter each time. Because the common servlet container implementation uses a thread to fulfill an HTTP request, then two different requests are guaranteed to use two different database connections.

Nayuki
  • 17,911
  • 6
  • 53
  • 80
Gabriel Belingueres
  • 2,945
  • 1
  • 24
  • 32
  • Your last comment applies here. I'm using the connection across a single request. Each request can go through many calls to functions needing the connection. For example, I'll use an id passed in the url to find a domain object in the database through a Finder class. Then I'll edit the object and update it in the database through some other class. Although I do close my result sets every time, I want the connection to be the same. – Sotirios Delimanolis Feb 25 '12 at 04:39
  • I still think it's reinventing the wheel. If you are going to run a servlet in a container (like Tomcat) use JNDI to lookup datasource and configure the datasource to pool connections for you. There are plenty of examples out there. – dbrin Feb 25 '12 at 05:38
  • Isn't that what sql DriverManager does when you do getConnection(); – Sotirios Delimanolis Feb 25 '12 at 05:47
  • No. DriverManager.getConnection() always opens a new connection, but it is a relativelly expensive operation, and if you are going to serialize the DB access, then you will only need one connection. Instead, you can configure a small connection pool by yourself, or even better, get one configured in your container, by obtaining a reference to a DataSource using JNDI. – Gabriel Belingueres Feb 25 '12 at 13:25
2

I know you said you don't want to use libraries to do this, but you're going to be way better off if you do. Pick a standard connection pool (C3P0, DBCP, or something) and you'll be way happier than if you bake your own. Why can't you use a library to do this?

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
0

I am not sure why you want your DB connections to be thread safe. Most of the time establishing connection to the database is the longest part of the transaction. Typically connections are reused between requests and pools of open connections are managed (via frameworks or more typically application servers).

If you are worried about concurrent modifications to the same tables you might want to look at synchronized methods: http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

dbrin
  • 15,525
  • 4
  • 56
  • 83
  • 1
    -1, using Java synchronization to protect the database transactions from colliding is a **terrible** idea – Steven Schlansker Feb 25 '12 at 04:28
  • I wouldn't do it in a regular app, but it sounds like this is some kind of small one off project where he wants to use no frameworks and wants to manage a connection pool internally. In this case it's not that a bad idea. Yes you are going to make other requests wait, but it gets the dirty job done. – dbrin Feb 25 '12 at 05:44
  • Doing it "the right way" isn't really that much harder, and this teaches terrible habits. It also leaves a huge amount of code debt that makes it nearly impossible to expand the scope of the application down the road. – Steven Schlansker Feb 25 '12 at 18:55