StringBuffer or StringBuilder in Servlet's doFilter method?
java
Solution
Local variables are thread-safe and variables declared inside the `doFilter()` method will be thread safe. Use `StringBuilder` for your purpose, as you shouldn't unnecessarily incur the overhead of synchronization used in `StringBuffer`.
Moreover , The Servlet request and response objects are created afresh for every new request and response and so by their nature they are thread safe. The `doFilter()` method will be executed in separate threads for each request.
Suggested Reading:
- Why are local variables thread safe in Java.
- StringBuilder and StringBuffer in Java
- servlet-filters tag wiki
Problem
I'm implementing my custom filter: ``` public class MyFilter implements javax.servlet.Filter ``` Which should I use in this `doFilter` method - StringBuffer or StringBuilder? I would like to use it in this way: ``` StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(MY_CODE_HERE); response.sendRedirect(stringBuffer.toString()); ``` or... ``` StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(MY_CODE_HERE); response.sendRedirect(stringBuilder.toString()); ``` I know that `StringBuffer` is thread safe, but would a `StringBuilder` be enough?