Reputation: 2138
I'm using Java NIO to implement a server.
For example, I will hold more than 10K connection. If the client did not send any data within 30 seconds, the server will kick off this client.
How to design such Timeout Timer efficiently?
My first thought was:
This is fine for small amount of connections. But, what if the size of connection queue increases? Will this solution still fit for 50K connections or more connections?
Upvotes: 0
Views: 597
Reputation: 310850
It would be better to keep a TreeMap of {time stamp, connection} pairs. That way you can position immediately to the 30-second-old point (with ceilingKey()) and just iterate over the actually timed-out items, not scan the whole list as you're planning to do here.
You don't really need the Executor task either, and multi-threading when Selectors are involved can make your life very difficult. Just process the timed-out connections at the bottom of the select() loop, or maybe use a 30-second select() timeout and only process them if select() returns zero. There are many ways to skin this cat.
Upvotes: 1