java - Java中PrintStream的线程安全

标签 java thread-safety printstream

我正在尝试写入一个文件。我需要能够“附加”到文件而不是覆盖它。另外,我需要它是线程安全和高效的。我目前的代码是:

private void writeToFile(String data) {
    File file = new File("/file.out");
    try {
      if (!file.exists()) {
        //if file doesnt exist, create it
        file.createNewFile();
      }
      PrintStream out = new PrintStream(new FileOutputStream(file, true));
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      Date date = new Date();
      out.println(dateFormat.format(date) + " " + data);

      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

一切都很好。我只是不知道 PrintStream 是否是线程安全的。所以,我的问题是:从多个 PrintStream 实例写入同一个物理文件安全吗?如果是这样,它是使用锁定(降低性能)还是排队? 您知道任何线程安全且使用队列的 native Java 库吗? 如果没有,我自己写也没问题。在我编写自己的代码之前,我只是想看看是否有本地的东西。

最佳答案

PrintStream 源表明它是线程安全的。

如果你想从不同的线程写入同一个文件,为什么不跨线程共享同一个 PrintStream 实例呢? PrintStream 为您进行同步。

/**
 * 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();
    }
}

关于java - Java中PrintStream的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632585/

相关文章:

java - Spring 和继承的线程安全

java - 方法调用后控制台输出不起作用

javascript - 从网站解析html代码并将其显示在java元素上

java - AES : Encryption with ECB mode in Java

java - 哪个基于 Java 的 Web 框架能够更好地防御 XSRF?

multithreading - 使用依赖注入(inject)时如何使共享资源线程安全?

java - 如何使用适用于 Mac 的 Oracle 新 1.7 JDK 运行 Eclipse?

c++ - Matlab引擎API的线程安全

java - 打印流输入到文本文件

java - 对 PrintStream out 变量感到困惑