我在一台TCP Server上工作,我想知道是否有可能同步AsynchronousSocketChannel的读写方法。我将通道包装到另一个类中,因为我的通道上需要一些额外的功能。我的问题是,这是否真的是同步的正确方式:
/**
* 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块?
发布于 2020-05-19 19:16:13
下面是我修复它的方法:
/**
* 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;
}
}https://stackoverflow.com/questions/61648281
复制相似问题