In my implementation of Java NIO, I was not able to get SelectionKey.attach () to work. Basically, as soon as clients connect (OP_ACCEPT ops interest), I add them to the map, where their IP address is mapped to an object that maintains state for the client. Then, when OP_READ happens, I retrieve the client IP address again and this time get the value from the card and get the client status object this way.
The problem here is that I need to do a map search. EVERY TIME data is read from the network. There is a lot of work. So, I was delighted that you can attach an arbitrary type of object to the SelectionKey, which should be easily retrieved when you call SelectionKey.attachment (), even if we are now processing another event (received during OP_READ and placed in map during OP_ACCEPT).
The problem is that it does not work. When I retrieve an attachment, it is always zero. And if I configure the application via attach (), and then immediately call attachment (), it will really work. Somehow between different events, he loses his connection.
Sorry, my code is a little long to post here, but if you look at the comments in this thread:
link text
... You will see that some others basically come to the same conclusion: attach () and attachment () are not work and never have.
Is there a trick to make it work, or am I stuck with the evil overhead needed to manually search the map EVERY TIME has a new reading event to process?
Finally, is there a way to “wrap” SelectionKey in a new subclass that will handle attach () and attachment () correctly?
Thanks!
source
share