【发布时间】:2017-10-15 02:38:08
【问题描述】:
考虑以下代码 sn-p,它只是将someByteBuffer 的内容写入标准输出:
// returns an instance of "java.nio.channels.Channels$WritableByteChannelImpl"
WritableByteChannel w = Channels.newChannel(System.out);
w.write(someByteBuffer);
Java 指定channels are, in general, intended to be safe for multithreaded access,而buffers are not safe for use by multiple concurrent threads。
所以,我想知道上面的 sn-p 是否需要同步,因为它在某个缓冲区(不是线程安全的)上调用通道的 write 方法(应该是线程安全的) .
我看了一下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;
}
}
请注意,除了方法中的前两行之外,所有内容都由writeLock 同步。现在,由于 ByteBuffer src 不是线程安全的,在没有适当同步的情况下调用 src.remaining() 是有风险的,因为另一个线程可能会更改它。
我应该在上面的 sn-p 中同步
w.write(someByteBuffer)行,还是我遗漏了一些东西,write()方法的 Java 实现已经解决了这个问题?
编辑:这是一个经常抛出BufferUnderflowException 的示例代码,因为我在最后注释掉了synchronized 块。删除这些 cmets 将使代码异常免费。
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();
}
}
}
【问题讨论】:
-
供将来参考:通道是线程安全的。例如,考虑在多个线程之间共享的打印机通道。如果所有线程都开始写入通道,它们的作业将不会交错。另一方面,如果多个线程可以访问打印机缓冲区,它们可以在打印过程中更改它,除非执行了适当的同步。
-
感谢您的快速接受;我很高兴能帮上忙。我也很欣赏这个写得很好,清晰的问题。最后加上“>”引用“摘要问题”的好主意!
-
@GhostCat:谢谢你!我想我很了解通道、缓冲区和线程安全发生了什么:)
标签: java multithreading concurrency buffer channel