java - 非阻塞读取大约需要 100 毫秒
问题描述
我正在使用 JAVA NIO,SocketChannel
如下所示:
while (true) {
int readyOperations = selector.select();
if (readyOperations == 0) {
continue;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
if (key.isReadable()) {
handleRead(key);
}
[...]
然后,在里面handleRead
我有这段代码:
public void handleRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buf = (ByteBuffer) key.attachment();
long nanoStart = System.nanoTime();
System.out.println("is channel blocking?: " + channel.isBlocking());
int bytesRead = channel.read(buf);
long nanoEnd = System.nanoTime();
System.out.println("elapsed time (ms): " + (nanoEnd - nanoStart) / 1000_000.0);
虽然我使用的是非阻塞通道,但第一次handleRead
被称为我得到了很大的经过时间。例如:
is channel blocking?: false
elapsed time (ms): 123
第一次handleRead
通话后,我得到了较小的值(< 0.5ms),elapsed time (ms)
这似乎是合理的。但是,偶尔我可以看到大约 10 毫秒的时间。
这似乎没有意义,因为我使用的通道是非阻塞的。为什么读取数据需要超过 1ms 的时间?经过的时间是否与在某个时间点读取的数据量有关?但是,即便如此,我预计一次读取约 1000 字节的成本将低于 <1ms。ByteBuffers
我使用的是ed allocateDirect
。
解决方案
推荐阅读
- android - 在 Android Google 地图中排序图层
- c++ - 将外部头文件导入 VS Code
- sql-server - Sql server 2017 开发人员设置失败,出现空白错误
- c# - DropShadowEffect 与半透明网格
- python-3.x - 如何使用python将列表保存到csv文件中
- c# - DateTime.UtcNow.AddMinutes((-1) * 300); 在 UTC 时间的打字稿中
- unity3d - 用于创建可以实时检测和跟踪随机对象位置的移动应用程序的技术?
- javascript - 如何使用 if & for 函数从 firestorage 数组值中查找特定行
- r - RShiny:与服务器断开连接
- docker - wait-for-it.sh 对于 Pentaho 服务器没有完全工作(8080 在服务器准备好登录之前就启动了)