Home » Java » StringBuffer or StringBuilder in Servlet's doFilter method? [duplicate]

StringBuffer or StringBuilder in Servlet's doFilter method? [duplicate]

Posted by: admin December 28, 2021 Leave a comment

Questions:

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?

Answers:

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:

  1. Why are local variables thread safe in Java.
  2. StringBuilder and StringBuffer in Java
  3. 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 synchronization.

Simply use 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 StringBuffer

###

As long as it is in the method doFilter(), its thread-safe and request scoped. So, StringBuilder is the obvious choice.

Ofcourse, unless there are multiple threads spawning within that method which modify it concurrently 🙂