Thread Safety of PrintStream in Java

我的梦境 提交于 2019-12-12 13:09:25

问题


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

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.


回答1:


The PrintStream source suggests that it is thread safe.

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


来源:https://stackoverflow.com/questions/21632585/thread-safety-of-printstream-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!