Reputation: 682
Has Non-blocking server, now it looks like:
ServerSocketChannel server = ServerSocketChannel.open();
// ... Many stuff like initialise selector, load world, etc
while(server.isOpen())
{
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext())
{
SelectionKey key = iterator.next();
switch(key.interestOps())
{
case SelectionKey.OP_ACCEPT:
// .... Accepting, register selector, packet handler etc
break;
case SelectionKey.OP_READ:
// .... Read-write stuff
break;
}
iterator.remove();
}
}
I need to e.g. 1 thread handles 100 connections. Other 100 connections handles another thread. I tried do it with this code:
public class ConnectionsHandler implements Runnable
{
private Selector selector;// For each thread gets its own selector
@Override public void run()
{
while(Server.server.isOpen())
{
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext())
{
SelectionKey key = iterator.next();
// .... Read-write stuff
iterator.remove()
}
}
}
}
But both threads after first accepted connection freezes... No any exception thrown, it's simply freezes.
Upvotes: 1
Views: 696
Reputation: 310860
register() is a blocking operation and so is select(). If getMostFreeSelector() returns the other selector and it is in select() at the time, the register() will block until the selector wakes up. You could call selector.wakeup() to fix this, or always register to the current selector, but I would question the whole architecture. Unless you have many thousands of connections there is little point in the second selector and thread.
Note also my comment above about the switch statement.
Upvotes: 1