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?
As StringBuilder is not synchronized, it is not thread safe but faster than StringBuffer. Use String, for a string which will be constant through out the application. Use StringBuffer, for a string which can change in multi-threaded applications. Use StringBuilder, for a string which can change in single-threaded applications.
Here, we compared StringBuffer objects using compareTo () method of java.lang.Comparable interface, after converting StringBuffer object into String object 3. Sorting Collection of StringBuilder: StringBuilder class too do not implements java.lang.Comparable interface, as shown in StringBuilder class signature above
Whereas for StringBuffer/StringBuilder which do not implements java.lang.Comparable interface like String class, therefore it is must to provide to custom-logic to sort by implementing java.util.Comparator interface and overriding compare () method Hope, you found this article very helpful.
StringBuilder was introduced in Java 5. StringBuffer is synchronized. This means that multiple threads cannot call the methods of StringBuffer simultaneously. StringBuilder is asynchronized. This means that multiple threads can call the methods of StringBuilder simultaneously. Due to synchronization, StringBuffer is called a thread safe class.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With