问题
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