Java NIO selector close idle connections?

M

meselfo

I have an object attached to all selectionKeys with a timestamp
showing last activity
on the connection. So how/when do i run through the keys to find
connections
that have been idle too long? Can i do it in the same main selector
loop that handles accept/read etc like this:

while (true) {

selector.select(sometimeout);
Iterator selectedKeys = selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
..process the selected key... accept/read etc..
}

if (timeToCheckForIdleConnections) {
Set<SelectionKey> k = selector.keys();
.. get attachment of all keys and check their timestamp for last
activity.. if idle for too long then close them!
}

}

or should I use a timethread that signals back to the main selector
thread which connections to close?
 
E

EJP

meselfo said:
or should I use a timethread that signals back to the main selector
thread which connections to close?

Do it in the same thread. Much simpler. If you're concerned about
performance, use a timed select and only do it when select() returns
zero, i.e. there are no ready channels and the selector is idle: that
way you don't hold anything up.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top