【问题标题】:How Synchronization works in StringBuffer?同步如何在 StringBuffer 中工作?
【发布时间】:2016-09-10 18:36:49
【问题描述】:

我一直读到 StringBuffer 是线程安全的,但我一直不明白它是如何实现的。我在文档的方法定义中没有看到任何 synchronized 关键字。 Java 是否使用 synchronized 块?所有方法都是synchronized吗?我相信只有更新底层对象的方法应该是synchronized

【问题讨论】:

  • 大部分方法都是synchronized。您可以通过在 IDE 中打开代码来查看。
  • source code。是的,大多数方法都是同步的。

标签: java multithreading synchronization stringbuffer


【解决方案1】:

字符串缓冲区可以安全地被多个线程使用。这些方法在必要时同步,以便任何特定实例上的所有操作都表现得好像它们以某种串行顺序发生,该顺序与所涉及的每个单独线程进行的方法调用的顺序一致。

https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html

如果您对如何详细实现感兴趣,请使用源代码安装 Oracle JDK,并直接查看 StringBuffer.java 或look here for an Apache Licensed online version

【讨论】:

  • 为什么读取方法是同步的?读取方法如何影响多线程操作。如果正在更新对象(尚未完成),则读取方法将返回旧值,这听起来是正确的。为什么要在读取时获取锁?
  • @codeCrawler:我只能看到带有以下签名的私有读取方法:private void readObject(java.io.ObjectInputStream s)
  • @Ravindrababu 通过阅读我的意思是像 length() getChars() 这样的方法,它们是同步的!
  • 那是安全防护。追加时,您不会得到中间结果,因为追加不会释放对象锁定,并且 length() 和 getChars() 将用于追加完成。
  • @Ravindrababu 如果在更新期间调用getChars() 会发生什么,它会返回旧值还是到目前为止更新的任何值?
【解决方案2】:

StringBuffer 是线程安全的。 append 方法已同步。

查看here了解更多详情。

/**
 * A thread-safe, mutable sequence of characters.
 * A string buffer is like a {@link String}, but can be modified. At any
 * point in time it contains some particular sequence of characters, but
 * the length and content of the sequence can be changed through certain
 * method calls.
 * <p>
 * String buffers are safe for use by multiple threads. The methods
 * are synchronized where necessary so that all the operations on any
 * particular instance behave as if they occur in some serial order
 * that is consistent with the order of the method calls made by each of
 * the individual threads involved.
public synchronized StringBuffer append(Object obj) {
    super.append(String.valueOf(obj));
    return this;
}

public synchronized StringBuffer append(String str) {
    super.append(str);
    return this;
}

编辑:

关于您的查询

如果在更新期间调用 getChars() 会发生什么,它会返回旧值还是到目前为止更新的任何值?

答案是:

getChars() 将等待其他同步方法完成执行并释放锁。

如果您参考文档的第二段,它清楚地引用了操作的行为,就好像它们按顺序发生一样。

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 2018-03-04
    • 2019-08-31
    • 2018-01-27
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多