Java StringBuilder and Thread Safety

I am building up a String out of multiple pieces and want to use either `StringBuffer` or `StringBuilder` to do so. From the Java 5 docs, I see that `StringBuilder` is preferred when possible, with the caveat that > Instances of `StringBuilder` are not safe for use by multiple threads. From this statement, I understand that I should not have a single `StringBuilder` instance shared by multiple threads. But what about this case: //Is this safe? //foo() is called simultaneously by multiple threads String foo(String a, String b) { return new StringBuilder(a).append(b).toString(); } Here there could be multiple threads in the function at the same time, using the `StringBuilder` class at the same time (eg, concurrent access of static variables, if there are any), but each thread would have its own separate instance of `StringBuilder`. From the documentation, I can not quite decide whether this counts as use by multiple threads or not.

以上就是Java StringBuilder and Thread Safety的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏