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:
- 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?
- In which scenario, StringBuffer has to be preferred over StringBuilder?