默认情况下 System.out.println 是线程安全的吗?
Is System.out.println thread-safe by default?
System.out
returns "standard" 输出流 - 一个 PrintStream
。 PrintStream
的 javadoc 没有告诉我关于线程安全的任何信息,而是查看 OpenJDK 和 OracleJDK 的源代码 告诉我 println
是同步的。
/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
这非常符合我的经验:调用 System.out.println()
从不同线程调用时从未创建 'mixed' 输出。
所以我的问题:
- 我可以依靠这种行为吗(使用不同的 JVM)?
- 是否有我遗漏的一些描述此行为的文档?
自 PrintStream
的文档以来,它的 superclass FilterStream
和 its superclass OutputStream
都没有提到线程安全或同步,理论上你不能依赖它,它不是契约的一部分。
我认为如果有人制作了一个 PrintStream
class 而没有像 Oracle 在这方面所做的那样,那将是 令人惊讶的 ,但我'以前也很惊讶。
System.out
returns "standard" 输出流 - 一个 PrintStream
。 PrintStream
的 javadoc 没有告诉我关于线程安全的任何信息,而是查看 OpenJDK 和 OracleJDK 的源代码 告诉我 println
是同步的。
/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
这非常符合我的经验:调用 System.out.println()
从不同线程调用时从未创建 'mixed' 输出。
所以我的问题:
- 我可以依靠这种行为吗(使用不同的 JVM)?
- 是否有我遗漏的一些描述此行为的文档?
自 PrintStream
的文档以来,它的 superclass FilterStream
和 its superclass OutputStream
都没有提到线程安全或同步,理论上你不能依赖它,它不是契约的一部分。
我认为如果有人制作了一个 PrintStream
class 而没有像 Oracle 在这方面所做的那样,那将是 令人惊讶的 ,但我'以前也很惊讶。