tags:

views:

45

answers:

1

I am creating a service that looks similar to this:

interface MyLogger
{
    void logStuff( int id, String message );
}

The implementation basically opens a file and caches an instance of the BufferedWriter in the class. The method is synchronized.

Is it ok to have an opened file wrapper by a BufferedWriter in a long live manner ?

A simplistic implementation of logStuff.

public void logStuff(...)
{
    try
    {
        this.writer.write( message );
        this.writer.flush();
    }
    catch( IOException ignored ) {}
}
+2  A: 

Yep, it's fine, you just need to be aware that other processes/threads may not be able to open the log file for writing while your service has it open. I think other processes can still open it read-only, though I don't know if that's system-dependent.

If other threads/processes do need to be able to write to the file intermixed with your service's writes, you could do something like caching log lines in the MyLogger instance; then once you have, say, 100, open the file in append mode, write them out, and close the file. That's not a particularly elegant thing to do, though.

David Zaslavsky