I know netty uses the Reactor pattern to avoid creating a thread for each connection,
the core concept about this pattern is a “selector” or epoll system call in Linux.
But I also heard about that if a handler never close it’s channel, it will occupy one worker thread and block it: doesn’t that mean each connetion will use (block) one thread,so for each accepted socket we still need to create a thread ?
for example ,if I write a server with 10,000 persistent connections,does this server need 10,000 worker threads??
The contradiction between those two things above confused me ,can anyone explain me if I understand it wrong? thank you~
========================================
an example (with only 1 worker thread ) which can always process one client’s event in the same time.
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class Netty_test {
public static void main(String[] args) {
ChannelFactory factory =new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newFixedThreadPool(1));
ServerBootstrap bootstrap = new ServerBootstrap(factory);
ChannelPipelineFactory cpf=new ChannelPipelineFactory(){
public ChannelPipeline getPipeline() {
return Channels.pipeline(new testHandler());
}
};
bootstrap.setPipelineFactory(cpf);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.bind(new InetSocketAddress(100));
}
}
class testHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
System.out.println("messageReceived, handler work.");
e.getChannel().write(e.getMessage());
ctx.sendUpstream(e);
}
}
No, your 10,000 connections will share the worker threads. One worker thread will handle multiple connections/channels. This is why it is very important not to block the worker threads.