我在阻塞上创建了一个ObjectInputSteam
and并试图同时读取和写入。我的代码是这样的:ObjectOutputStream
SocketChannel
socketChannel = SocketChannel.open(destNode);
objectOutputStream = new ObjectOutputStream(Channels.newOutputStream(socketChannel));
objectInputStream = new ObjectInputStream(Channels.newInputStream(socketChannel));
Thread replyThread = new Thread("SendRunnable-ReplyThread") {
@Override
public void run() {
try {
byte reply = objectInputStream.readByte();//(A)
//..process reply
} catch (Throwable e) {
logger.warn("Problem reading receive reply.", e);
}
}
};
replyThread.start();
objectOutputStream.writeObject(someObject);//(B)
//..more writing
问题是行 (B) 处的写入阻塞,直到行 (A) 处的读取完成(阻塞返回的对象SelectableChannel#blockingLock()
)。但是应用程序逻辑规定,在所有写入完成之前,读取不会完成,因此我们有一个有效的死锁。
SocketChannel
javadocs说支持并发读写。
当我尝试常规的 Socket 解决方案时,我没有遇到这样的问题:
Socket socket = new Socket();
socket.connect(destNode);
final OutputStream outputStream = socket.getOutputStream();
objectOutputStream = new ObjectOutputStream(outputStream);
objectInputStream = new ObjectInputStream(socket.getInputStream());
但是,我无法利用FileChannel#transferTo(...)