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());
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?
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
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.
- Why are local variables thread safe in Java.
- StringBuilder and StringBuffer in Java
- servlet-filters tag wiki
Since it will be a local variable and not shared by threads, StringBuilder can be used.
StringBuilder is a better choice as it is faster because of its non-synchronized nature. ServletFilter doFilter for each request run in its own thread so you don;t need a synchronized datastructure. And if it is simply a local varibale then StringBuilder is the choice.
StringBuilder is designed as drop-in replacement for
StringBuffer without the
StringBuilder unless you are really trying to share a buffer between threads.
StringBuilder is the unsynchronized relative of the original synchronized StringBuffer class.
In your case
StringBuilder makes perfect sense. Even in other case, consider synchronizing method then using
As long as it is in the method doFilter(), its
request scoped. So,
StringBuilder is the obvious choice.
Ofcourse, unless there are multiple threads spawning within that method which modify it concurrently 🙂