1

A class I wrote in charge of logging uses FileWriter to write into a file defined by the developer.

A colleague mentioned that I should check the thread safety of this logger, since it will be used by multi-threaded web frameworks, namely Spring boot.

The critical section, which writes to file, looks something like this:

public void write(String s) {
    FileWriter fw;
    try {
        fw = new FileWriter(new File(outputFilePath), true);
        fw.write(s);
        fw.close();
    } catch (IOException ex) {
        throw ex;
    }
}

outputFilePath is set upon construction. So all threads are writing to the same file concurrently. The construction of this class uses Factory Method which looks like this:

Audit auditLogger = LoggingFactory.createAuditLogger(outputfilepath);

I remember from college that 'Appending to tables/files is thread safe', but this claim is too broad to make me feel comfortable about this code.

How do I approach questions of thread safety? And what about this one in particular?

Thanks

Airwavezx
  • 898
  • 5
  • 14
  • 26
  • 1
    why are you not using log4j or similar? But anyway, what have you considered so far? synchronized? – Scary Wombat Jun 21 '18 at 08:06
  • Well, to start with, it's going to be slow - opening and close the file is expensive. If something goes wrong, you run the risk the file been left open - better to use `try-with-resources`. Multiple threads could attempt to open the same file and write to it. AFIA `FileWriter` is not thread safe. A better approach might be to use a produce/consumer approach, where a single thread reads the message from a blocking queue and writes when it becomes available, but multiple threads can post messages to the queue - as an off the head idea – MadProgrammer Jun 21 '18 at 08:10
  • I would suggest adding the String to a BlockingQueue and creating a seperate thread which polls the BlockingQueue and write to the files.. – akshaya pandey Jun 21 '18 at 08:11
  • Note, the title of your question says "FileWriter", but the code snippet that you showed can not possibly allow any single `FileWriter` instance to be used by more than one thread. Your question really goes much deeper. You really are asking what happens when different threads use different file handles to write the same file. That's probably not even a Java question. (I don't see the word "thread" anywhere in the documentation for `FileWriter` or, for `File`.) You really are asking a question about whatever operating system your code will happen to run on. – Solomon Slow Jun 21 '18 at 15:53
  • I second Akshaya Pandey's suggestion. Dedicate a single thread to writing the file. – Solomon Slow Jun 21 '18 at 15:54

0 Answers0