Question

I have a method which is synchronized. I want to use a string buffer to form a long concatenated string. I know both StringBuffer and StringBuilder can do this job. At the same time, I think StringBuilder is better since it will not incur any additional synchronization costs as the method already does that.

What do you say?

Was it helpful?

Solution

As long as multiple threads aren't accessing the StringBuilder itself or causing it to be accessed in a concurrent manner, then you should be fine.

In your case, if the method the StringBuilder/Buffer is in is synchronized, only one thread should have access to it at any one time, so a StringBuilder should suffice.

OTHER TIPS

If you are managing thread safety from your side then StringBuilder is good option and in latter case StringBuffer would be better.

Managing thread safety from yourself is always better because sometimes you have very small critical section in your code so there method level Synchronization is not necessary only block level is enough but in methods like StringBuffer sometimes synchronization causes a high cost but anyway it's up to your need.

As your object of StringBuilder is not shared with other threads , you can use that..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top