I created an ObjectInputSteam and an ObjectOutputStream when locking the SocketChannel and trying to read and write at the same time. My code looks something like this:
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();
The problem is that the records in row (B) are locked until the reading in row (A) has finished (blocks on the object returned by SelectableChannel#blockingLock() ). But the application logic requires that the reading does not end until all records have completed, so we have an effective deadlock.
SocketChannel javadocs say concurrent reads and writes are supported.
I had no such problem when I tried the correct Socket solution:
Socket socket = new Socket(); socket.connect(destNode); final OutputStream outputStream = socket.getOutputStream(); objectOutputStream = new ObjectOutputStream(outputStream); objectInputStream = new ObjectInputStream(socket.getInputStream());
However, I cannot take advantage of the performance of FileChannel#transferTo(...)
java sockets nio
Kevin wong
source share