gpt4 book ai didi

java - AsynchronousSocketChannel Read/WritePendingException - 可以同步吗?

转载 作者:行者123 更新时间:2023-12-01 16:53:07 24 4
gpt4 key购买 nike

我正在开发一个TCP服务器,我很好奇是否可以同步AsynchronousSocketChannel的读取和写入方法。我将 channel 包装到另一个类中,因为我的 channel 需要一些附加功能。我的问题是这是否真的是同步的正确方法:

/**
* writes bytes from a <b>ByteBuffer</b> into an
* <b>AsynchronousSocketChannel</b>
*
* @param buffer the ByteBuffer to write from
* @param onFailure specifies the method that should be called on failure of the
* write operation
*/
public void write(ByteBuffer buffer, final C onFailure) {

CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {

@Override
public void completed(Integer result, ByteBuffer buf) {
if (buf.hasRemaining())
channel.write(buf, buf, this);
}

@Override
public void failed(Throwable exc, ByteBuffer buf) {
attachment.call(onFailure, exc);
}

};

synchronized (writeLock) {
this.channel.write(buffer, buffer, handler);
}
}

在本例中,writeLock 是一个static final 对象,当我的包装类的任意实例开始写入操作时,它会获取锁。这真的有效还是只是用完了同步块(synchronized block)?

最佳答案

这就是我修复它的方法:

/**
* writes bytes from a <b>ByteBuffer</b> into an
* <b>AsynchronousSocketChannel</b>
*
* @param buffer the ByteBuffer to write from
* @param onFailure specifies the method that should be called on failure of the
* write operation
*/
public void write(ByteBuffer buffer, final C onFailure) {

CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {

@Override
public void completed(Integer result, ByteBuffer buf) {
if (buf.hasRemaining()) {
channel.write(buf, buf, this);
return;
}

synchronized (writeLock) {
if (!writeQueue.isEmpty()) {
while (writePending)
;

ByteBuffer writeBuf = writeQueue.pop();
channel.write(writeBuf, writeBuf, this);
writePending = true;
return;
}
}

writePending = false;
}

@Override
public void failed(Throwable exc, ByteBuffer buf) {
writePending = false;
attachment.call(onFailure, exc);
}

};

synchronized (writeLock) {
while (this.writePending)
;

this.writeQueue.push(buffer);

ByteBuffer writeBuffer = this.writeQueue.pop();
this.channel.write(writeBuffer, writeBuffer, handler);
this.writePending = true;
}
}

关于java - AsynchronousSocketChannel Read/WritePendingException - 可以同步吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61648281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com