0
votes

I am using the Tomcat JDBC connection pool.

In a multi thread scenario, is it safe to use a static instance of the DataSource object?

This is how I am getting my connection when needed:

 public static Connection getConnection() throws SQLException {
        return datasource.getConnection();
      }

After I run my querie(s) I make sure the close the connection.

1
Is your datasource marked as final? For safe-publication purposes datasource reference should be marked as final.rvit34
It is not, this is how I defined it: private static DataSource datasource;Federico
It's not thread-safe thenrvit34
@rvit34 It is possibly not thread-safe, but if the field is only assigned once, then it probably is thread-safe (apart from possible publication issues).Mark Rotteveel
I modified the datasource instantiation as: private static final DataSource datasource = new DataSource(); and I set the properties as follows: public static void initializeConnection(Properties properties) { PoolProperties poolProp = setPoolProperties(properties); datasource.setPoolProperties(poolProp); } This is called only once at beginning, before other threads get created.Federico

1 Answers

1
votes

Generally, yes. While the DataSource interface does not specify this explicitly, typically you'd use some connection pooling DataSource implementation in an application server, which is typically designed to work well in multi threaded environments. On paper some implementations might actually be mutable but typically that should not be the case.