Java NIO:避免HashMapNode内存分配吗?

时间:2018-10-10 09:58:35

标签: java nio

经典NIO客户端:

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,并以较小的超时时间(例如10ms)调用select(),如果要写入的缓冲区不为空,则注册WRITE,进行写入,然后再次注册READ ,内存分配问题已解决,但由于必须等待READ select timeout,因此写操作将被延迟。

还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

好的,我想我明白了。在这里。

主循环:

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()