StringBuffer or StringBuilder use in a Web Application DAO

时间:2015-09-14 16:00:32

标签: java multithreading spring-mvc spring-jdbc

Conventional wisdom states that java developers should normally use the StringBuilder class in preference to the StringBuffer class. As the StringBuilder class methods are not synchronised, they are normally much faster than the StringBuffer equivalents.

I have a spring framework based web application that runs on a servlet container (i.e. apache tomcat). In a Database Access Object class, I have a method that builds a SQL statement and then executes it against a database via a JDBC data source connection (encapsulated within a transaction).

To date, the method has used a StringBuffer to build the SQL statement. As beans created by the spring framework are singletons by default, and the servlet container hosting the application creates new threads for each request it receives (in effect, the application will be executing in multiple threads simultaneously), this means that multiple threads will be making calls to a single instance of the DAO.

I was always under the impression that local variables are thread safe in java (I vaguely recall something about local variables being allocated in the stack and that threads don't share their stack). The aforemetioned StringBuffer used in our DAO method is declared and instantiated within that method.

In this situation, should we stick with the (thread-safe) StringBuffer, or can we move to the (supposedly much faster) StringBuilder?

1 个答案:

答案 0 :(得分:3)

Yes, method local variables are thread-safe. Using StringBuilder would be more efficient.