Java StringBuilder 和线程安全

发布于 2024-07-15 00:38:22 字数 603 浏览 6 评论 0原文

我正在用多个片段构建一个字符串,并希望使用 StringBufferStringBuilder 来执行此操作。 从 Java 5 文档中,我发现尽可能首选 StringBuilder,但需要注意的是

StringBuilder 的实例对于多线程使用并不安全。

从这个声明中,我了解到我不应该有一个由多个线程共享的 StringBuilder 实例。 但是这种情况呢:

//Is this safe?
//foo() is called simultaneously by multiple threads
String foo(String a, String b) {
    return new StringBuilder(a).append(b).toString();
}

这里函数中可能同时有多个线程,同时使用 StringBuilder 类(例如,并发访问静态变量,如果有的话),但每个线程都有自己单独的 StringBuilder 实例。 从文档中,我无法完全确定这是否算作多线程使用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

情未る 2024-07-22 00:38:22

那就完全没问题了。 局部变量只要不访问或改变实例或类变量,就不存在线程安全问题。

That's perfectly fine. Local variables have no problems with thread safety as long as they don't access or mutate instance or class variables.

太阳男子 2024-07-22 00:38:22

是的,这是安全的,因为 StringBuilder 对象仅在本地使用(每个调用 foo() 的线程都会生成自己的 StringBuilder)。

您还应该注意,您发布的代码实际上与由此生成的字节码相同:

String foo(String a, String b) {
    return a + b;
}

Yes, that is safe, because the StringBuilder object is used only locally (each thread calling foo() will generate its own StringBuilder).

You should also note that the code you posted is practically identical to the bytecode generated by this:

String foo(String a, String b) {
    return a + b;
}
少跟Wǒ拽 2024-07-22 00:38:22

您拥有的代码是安全的。

这段代码不是。

public class Foo
{
    // safe
    private final static StringBuilder builder;

    public static void foo()
    {
        // safe
        builder = new StringBuilder();
    }

    public static void foo(final String a)
    {
        // unsafe
        builder.append(a);
    }

    public synchronized void bar(final String a)
    {
        // safe
        builder.append(a);
    }
}

仅使用本地数据的本地变量不存在线程安全问题。 只有当您开始处理在类或实例方法/变量级别可见的数据时,您才会遇到线程安全问题。

The code you have is safe.

This code is not.

public class Foo
{
    // safe
    private final static StringBuilder builder;

    public static void foo()
    {
        // safe
        builder = new StringBuilder();
    }

    public static void foo(final String a)
    {
        // unsafe
        builder.append(a);
    }

    public synchronized void bar(final String a)
    {
        // safe
        builder.append(a);
    }
}

Local variables that only make use of local data do not have threadsafe issues. You can only have threadsafe issues once you start dealing with data that is visible at the class or instance method/variable level.

沫离伤花 2024-07-22 00:38:22

同意其他答案——只是一个注释。

如果存在 StringBuffer 被多个线程使用的情况,那么它可能是一个完全损坏的用例,因为这意味着单个字符串是以准随机顺序构建的,因此使 StringBuffer 成为线程是没有意义的安全的。

Agree with the other answers--just a note.

If there was a case where StringBuffer was being used by multiple threads, it's probably a completely broken use case because it would mean a single string was being built up in a quasi-random order, so it wouldn't make sense to make StringBuffer thread safe.

瀟灑尐姊 2024-07-22 00:38:22

我不确定是否需要这段代码,因为我猜 Java 会自动选择 StringBuilder。 如果没有性能问题,请选择 a + b。

如果需要性能,请尝试:

return new StringBuilder(
a.length() + b.length()).append(a).append(b).toString();

正确调整缓冲区大小并防止虚拟机调整缓冲区大小并创建垃圾以进行收集。

I am not sure if this code is needed, because Java picks the StringBuilder automatically I guess. If you do not have a performance problem, go with a + b.

In case of a performance need, try that:

return new StringBuilder(
a.length() + b.length()).append(a).append(b).toString();

It correctly sizes the buffer and prevents the VM from resizing it and creating garbage to collect on the way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文