1

When using Java NIO, I got some problems.

I need to change the interestOps of a key. I found here are two ways to do it.

First is done by invoking key.interestOps():

key.interestOps(OP_READ)

However I encountered with very tricky thread-safe issues in this way:

key.interestOps(OP_WRITE);
sl.select();  
Iterator iter = sl.selectedKeys().iterator();
log(iter.toArray().length); // Sometimes, I got 0 here!

The interesting thing is I got 0 sometimes in log (But sometimes it just works well). But there is no explicit modification of key in other threads. I can't understand what happened between the line2 and line3.

Another way is to register again:

The problem is the new return key lost his buffer:

key = sockChannel.register(selector, OP_WRITE);
key.attach(buf);
sockChannel.register(selector, OP_READ);
key.attachment();// nullExcetion here!

Of course this can be fixed by reassigning the buffer, but I'm sure things can be better.

Any insights?

4

1 回答 1

-1

我应该说 Java NIO 中的线程安全问题非常棘手。最好避免它而不是弄清楚它。这就是Rox Java NIO 教程 http://rox-xmlrpc.sourceforge.net/niotut/的作者所倡导的理念,这是一本非常好的 NIO 新手教程。许多技巧和原则非常有用。我个人会向所有想深入研究 Java NIO 的人推荐本教程。阅读它,你可以学到很多东西。

于 2013-09-08T12:16:14.800 回答