Multiple threads write data to a file. When maxLines
is reached, the file is closed and a new file is created:
public synchronized void writeLine(String data) throws IOException {
writer.write(data + "\n");
lineCounter++;
if(maxLines != 0 && lineCounter == maxLines) {
close();
lineCounter = 0;
fileCounter++;
addFile();
open();
}
}
As you can see I currently solved this with a synchronized
method. This ensures that thread 1 won't write when thread 2 just closed the writer
.
I think that's pretty slow. Is there a better solution for this? Maybe with lineCounter
as volatile
?
writer
exactly? \$\endgroup\$writer
is aBufferedWriter
\$\endgroup\$