Java中PrintStream的线程安全性 [英] Thread Safety of PrintStream in Java

查看:135
本文介绍了Java中PrintStream的线程安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写入文件.我需要能够附加"到文件而不是覆盖它.另外,我需要它是线程安全和高效的.我当前拥有的代码是:

I am trying to write to a file. I need to be able to "append" to the file rather than write over it. Also, I need it to be thread safe and efficient. The code I have currently is:

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实例写入同一物理文件是否安全?如果是这样,它是否使用锁定(降低性能)或排队? 您是否知道任何本机Java库都是线程安全的并且使用队列? 如果没有,我写自己的书就没问题.我只是想在写自己的东西之前先看看是否有本机.

It all works great. I just do not know if PrintStream is thread-safe or not. So, my question: Is writing to the same physical file from several instances of PrintStream safe? If so, does it use locking (reduces performance) or queueing? Do you know of any native java libraries that are thread-safe and use queueing? If not I have no problem writing my own. I am simply trying to see if there is anything native before I go write my own.

推荐答案

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

The PrintStream source suggests that it is thread safe.

如果要从不同的线程写入同一文件,为什么不跨线程共享同一PrintStream实例? PrintStream为您完成同步.

If you want to write to the same file from different threads, why not share the same PrintStream instance across the threads? The PrintStream does the syncing for you.

/**
 * 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中PrintStream的线程安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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