Search code examples
javamultithreadingfile-ioiofilewriter

Why are the write(..) methods java.io.Writer synchronized?


I am using java.io.FileWriter to write some data to the disk. As you know, FileWriter extends OutputStreamWriter, which in turn extends Writer.

When I looked at Writer's write(..), to my amazement it is synchronized.

**java.io.Writer**

    public void write(int c) throws IOException {
        synchronized (lock) {
            if (writeBuffer == null){
                writeBuffer = new char[WRITE_BUFFER_SIZE];
            }
            writeBuffer[0] = (char) c;
            write(writeBuffer, 0, 1);
        }
    }

I am curious as to why the writes are synchronized in the base Writer class? For my use case, I only have one writer thread and have absolutely no need for writes(..) to be synchronized.

I am aware that acquiring un-contended locks are much faster than contended locks. However, this whole business of having the base Writer class synchronized doesn't look like a good design to me.

Is there an un-synchronized Writer class that I have missed?

Thanks


Solution

  • I am curious as to why the writes are synchronized in the base Writer class?

    This implementation will work correctly whether you need it to be thread safe or not. This means it will work with the widest range of use cases.

    For my use case, I only have one writer thread and have absolutely no need for writes(..) to be synchronized.

    If you only ever lock an object using the same thread each time, it will do this very efficiently (if you have biased locking enabled which is the default)

    Is there an un-synchronized Writer class that I have missed?

    It has a very small overhead which you can measure in CPU bound tasks but it will be around 1/1000th the delay of the actual write to IO. i.e. you won't be able to tell the difference for you use case.