Search code examples
javaspringmultithreadingsingletonspring-ioc

Should the singleton methods be synchronized?


My web-app (the is no Spring-MVC here, only core IOC) using a lot of prototype beans and most of them are using a singleton dao-bean. Should the singleton dao-bean methods be synhronized since many different prototype beans (from different requests) may use the same method id dao in the same moment?

For example, the dao method

public void setLetterNotNew(int letterId) {

    final String sql = "UPDATE income SET isnew=? WHERE id=?";

    try( Connection con = HikariFactory.getConnection(); PreparedStatement ps = con.prepareStatement(sql); ) {

        ps.setInt(1, 0);
        ps.setInt(2, letterId);

        int i = ps.executeUpdate();
        if(i==0) throw new SQLException("setLetterNotNew");

    } catch (SQLException e) {
        log.error(e);
    }
}

Solution

  • It depends.

    As you wrote in a comment, you use jdbc. All operations on JDBC API are synchronized and do auto-commit by default. So if you share your JDBC connection but your method doesn't need a transaction (for example it doesn't do an update on data that was selected few lines before) than it doesn't need to be synchronized.

    However, if you need transactions, than you either have to synchronize this method or provide each thread with it's own JDBC connection, as each connection is also a transaction. To achieve that you could open new connection each time in a method or let Spring handle that problem