Writing buffers to a Java channel: Thread-safe or not?

Viewed 2623

Consider the following code snippet, which simply writes the contents of someByteBuffer to the standard output:

// returns an instance of "java.nio.channels.Channels$WritableByteChannelImpl"
WritableByteChannel w = Channels.newChannel(System.out);
w.write(someByteBuffer);

Java specifies that channels are, in general, intended to be safe for multithreaded access, while buffers are not safe for use by multiple concurrent threads.

So, I was wondering whether the above snippet requires synchronization, as it is invoking the write method of a channel (which is supposed to be thread-safe) on some buffer (which is not thread-safe).

I took a look at the implementation of the write method:

public int write(ByteBuffer src) throws IOException {
    int len = src.remaining();
    int totalWritten = 0;
    synchronized (writeLock) {
        while (totalWritten < len) {
            int bytesToWrite = Math.min((len - totalWritten),
                                        TRANSFER_SIZE);
            if (buf.length < bytesToWrite)
                buf = new byte[bytesToWrite];
            src.get(buf, 0, bytesToWrite);
            try {
                begin();
                out.write(buf, 0, bytesToWrite);
            } finally {
                end(bytesToWrite > 0);
            }
            totalWritten += bytesToWrite;
        }
        return totalWritten;
    }
}

Notice that everything is synchronized by the writeLock, except the first two lines in the method. Now, as the ByteBuffer src is not thread-safe, calling src.remaining() without proper synchronization is risky, as another thread might change it.

Should I synchronize the line w.write(someByteBuffer) in the above snippet, or am I missing something and the Java implementation of the write() method has already taken care of that?

Edit: Here's a sample code which often throws a BufferUnderflowException, since I commented out the synchronized block at the very end. Removing those comments will make the code exception free.

import java.nio.*;
import java.nio.channels.*;

public class Test {
    public static void main(String[] args) throws Exception {

        ByteBuffer b = ByteBuffer.allocate(10);
        b.put(new byte[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', '\n'});

        // returns an instance of "java.nio.channels.Channels$WritableByteChannelImpl"
        WritableByteChannel w = Channels.newChannel(System.out);

        int c = 10;
        Thread[] r = new Thread[c];
        for (int i = 0; i < c; i++) {
            r[i] = new Thread(new MyRunnable(b, w));
            r[i].start();
        }
    }    
}

class MyRunnable implements Runnable {
    private final ByteBuffer b;
    private final WritableByteChannel w;

    MyRunnable(ByteBuffer b, WritableByteChannel w) {
        this.b = b;
        this.w = w;
    }

    @Override
    public void run() {
        try {
            // synchronized (b) {
                b.flip();
                w.write(b);
            // }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
2 Answers
Related