Is it safe to call write
on Java FileOutputStream
object form multiple threads? Will the output be serialized correctly?
clarification:
In my case the class logger holds a FileOutputStream reference, and multiple threads can call logger write, that formats the output and calls FileOutputStream write.
Should I synchronize my logger write method to warrant that the messages from multiple threads are not mixed?
For your use case you would use a synchronized queue and modify each of your worker threads to add their log data to the master queue that the log thread uses for logging. You should NOT have multiple threads trying to write directly to the same file.
You can have multiple threads write to the same file - but one at a time. All threads will need to enter a synchronized block before writing to the file. In the P2P example - one way to implement it is to find the size of the file and create a empty file of that size.
FileOutputStream writes bytes with the following write methods : write(byte[] b) — writes array of bytes to the file output stream. write(byte[] b, int off, int len) — writes len bytes from the specified byte array starting at offset off to the file output stream.
FileOutputStream fout=new FileOutputStream(“file. txt”); Reading data from DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream .
A file can not be opened more than once in write-mode
, so the answer is no.
After seeing your edit, yes you should introduce synchronization into your logger to make sure the stream is accessed only by one thread at a time. Just a suggestion, why don't you go for Log4J? It already handles your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With