【问题标题】:Java NIO: Avoid HashMapNode memory allocations?Java NIO:避免 HashMapNode 内存分配?
【发布时间】:2018-10-11 12:19:58
【问题描述】:

经典蔚来客户端:

Create a selector
Register channel to selector for READ WRITE
Loop: 
   select
   iterate selectedKeys
       do work for Readable channel and Writeable channel

我像上面一样为android编写了一个简单的UDP NIO客户端,但发现每10秒就有30k+ HashMapNode内存分配。由于通道同时涉及 READ 和 WRITE,因此 select() 调用由于它是可写的而立即返回,在每个 select() 期间,至少一个 SelectionKey 被添加到 SelectedKeys() 返回的 HashMap 中。 我将设计更改为在开始时仅注册 READ,并以较小的超时时间(例如 10 毫秒)调用 select(),如果要写入的缓冲区不为空,则注册 WRITE,进行写入,然后再次注册 READ , 内存分配问题已修复,但写入操作会延迟,因为您必须等待 READ 选择超时。

有更好的方法吗?

【问题讨论】:

  • 或者我应该在添加一些东西写入缓冲区之后立即添加一个 selector.wakeup() 调用吗?

标签: java nio


【解决方案1】:

好的,我想我明白了。就这样吧。

主循环:

Open channel and configureBlocking(false)
Open selector
Register channel to selector, only concern about OP_READ
LOOP:
    selector.select() // No timeout
    if write buffer is empty or no channel been selected, continue
    LOOP for selectionKey in selectedKeys:
        if selectionKey is readable
             do read operation
        else if selectionKey is writeable
             do write operation
             register channel to OP_READ
        remove selectionKey from selectedKeys          

写:

write data to write buffer
register channel to OP_WRITE
selector.wakeup()

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多