这段代码中的 StringBuilder 变量线程安全吗? [英] Is that StringBuilder variable thread safe in this code?

查看:36
本文介绍了这段代码中的 StringBuilder 变量线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的 struts Action 类,其中我在 execute 方法中使用了一个 StringBuilder 变量.我的问题:变量 sb 是否是线程安全的?

Consider the below struts Action class in which, I am using a StringBuilder variable inside the execute method. My question: Is the variable sb threadsafe or not?

public DemoAction extends Action
{
    ......

    public ActionForward execute(.....)
    {
       StringBuilder sb = new StringBuilder();
    }
}

如果在 execute() 之外声明了相同的变量 sb 呢?还记得 WebContainer 中 DemoAction 只有一个对象吗?

What if the same variable sb declared outside the execute(). Remember there will be only one object for DemoAction in WebContainer.?

推荐答案

局部变量是线程安全的,只要没有其他线程以某种方式获得对同一个字符串构建器实例的引用,它就是线程安全的.

Local variables are thread safe, as long as no other thread somehow gets a reference to the same string builder instance, it’s thread safe.

这篇关于这段代码中的 StringBuilder 变量线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆