0

The only/major difference between StringBuffer and StringBuilder is StringBuffer is thread safe and StringBuilder is not.

So use StringBuilder when it is going to be accessed from a single thread and use StringBuffer when it is going to be accessed from multiple threads.

Let's consider an example of a servlet:

public class MyClass extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      StringBuilder sb1 = new StringBuilder();
  }
}

Now when the request comes to the servlet container new thread will be created, so get method in above example will be accessed from multiple threads.

Question is:

  1. Is it un-syncronized nature of StringBuilder is an issue here, will the same StringBuilder shared across threads or it is declared in method hence every thread will have separate StringBuilder?
  2. In which scenario, StringBuffer has to be preferred over StringBuilder?

2 Answers 2

3

sb1 is a local variable, so each thread will have it's own instance (each thread will execute that new StringBuilder() sentence). It is totally safe using StringBuilder in this case.

It would be a problem if your code were like this:

public class MyClass extends HttpServlet {

   private StringBuilder sb1 = new StringBuilder();

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  }
}

In this case you'd have issues because all the threads use the same MyClass instance because the container just creates one instance of each servlet that is shared by all the threads.

Please notice also that in this case even a StringBuffer would have problematic, because the operations on that attribute would be "atomic" (sychronized) but you could not ensure the order of accessing to that resource and the results could be messy.

Sign up to request clarification or add additional context in comments.

Comments

0

1) In servlet context every servlet instance is shared between multiple requests. So if you create an instance variable for the servlet you may occur to thread safe problem because every request share the same memory also instance variables. In you case the StringBulder instance is created inside the doGet method so you can't occur to that problem. Alternative is using thread synchronization

2) Maybe using StringBuffer can be better because you have to not redeclare the local variable every time

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.