Java:SelectionKey. Is attach () broken?
In my java NiO implementation, I cannot make selectionkey Attach () works Basically, once the clients connect (op_accept interest operation), I add them to a map where their IP addresses are mapped to an object that maintains the client state Then, when op_ When read occurs, I retrieve the IP address of the client again. This time, I get the value from the map and get the status object of the client in this way
The problem here is that I have to search the map every time I read data from the network There is a lot of wasteful work there So, I'm glad to see that you can attach an arbitrary object type to the selectionkey when you call selectionkey When attachment(), it should be easy to retrieve, even if we are now dealing with a different event (retrieved during op_read rather than put into the map during op_accept)
The problem is that it doesn't work When I retrieve an attachment, it is always null If I set an attachment through attach () and then immediately call attachment (), it does work Somehow, it lost its association
Sorry, my code is a little long here, but if you look at the comment in this post: link text... You will see that others basically come to the same conclusion: attach() and attachment() don't work, and never
Is there a trick to make it work, or do I insist on manually performing the evil overhead of finding in the map, with a new read event to deal with each time?
Finally, is there a way to "wrap" the selectionkey in a new subclass that will handle attach () and attachment () correctly?
thank you!
Solution
I successfully attached the object to selectionkeys without any problems, but only from the same event For example, I won OP for the first time_ When I read, I attach an object to the selectionkey and retrieve it on subsequent reads. It works normally Maybe op_ Accept and op_ Read handles different keys because they are different events, but I think the selectionkey should be the same for the same connection... But if you use the same IP to establish different connections, you will get different selectionkeys
Update: I just checked my code and there's something very important: I didn't call attach (); I used selectablechannel Register (selector SEL, int OPS, object ATT) method If you do, subsequent calls to attachment () on selectionkey will work