Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to FileOutputStream from multiple threads in Java

Tags:

java

file-io

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?

like image 268
José Avatar asked Dec 07 '11 20:12

José


People also ask

Can multiple threads write to the same file Java?

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.

Can two threads write 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.

How do I write with FileOutputStream?

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.

How do you create a FileOutputStream file in Java?

FileOutputStream fout=new FileOutputStream(“file. txt”); Reading data from DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream .


1 Answers

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.

like image 56
GETah Avatar answered Oct 21 '22 00:10

GETah