10000 conexão simultânea usando Java NIO

Eu escrevi um servidor (semelhante a umaqui) eCódigo do cliente usando Java nio.

Estou tentando alcançar o maior número possível de conexões. A partir de sugestões anteriores, diminuí a velocidade do processo de criação de clientes, dando ao sistema operacional (Windows 8) tempo suficiente para lidar com as solicitações.

Eu executei o código do cliente em uma máquina diferente para que o servidor tenha todo o espaço disponível para execução.

Quando tento criar 10.000 conexões, cerca de 8500 estão sendo conectadas e o restante é recusado para conexão, e a recusa de conexão para clientes (threads no código do cliente) acontece mais, que é criada posteriormente (para loop no código do cliente).

O uso de CPU e memória aumenta drasticamente. Crie um perfil para ver a maioria (48% do consumo total de CPU) é consumida pelo método select (restante principalmente por eventos da GUI). É devido a tantos clientes? Também vi algumas pessoas reclamando sobre esse bug no JRE7 e sugerindo o uso do JRE6.

O uso da memória tem mais de 2000 MB parajavaw.exe (notei 1 processo que estava usando pouca memória, mas tinha grande uso de CPU). Em geral, usamos cerca de 98% quando todos os 8500 clientes estavam conectados. O sistema travou demais por muitas vezes, mas continuou a funcionar.Eu vi o uso de memória em pool não-página aumentada durante o processo de 178 MB para 310 MB (qual é o limite máximo?). É porque quando escrevemos nos soquetes Não-página memória agrupada é usada?

Alguém pode dizer quais limites posso estar atingindo para que as 10.000 conexões bem-sucedidas não sejam possíveis? (Soquete por limite de processo?) (Memória não paginada?) (Fila de lista de pendências novamente?) Ajustes que podem permitir que os limites sejam empurrados? (Máquina Windows)

Estou usando o Windows 8 em um sistema de 4 GB.

`

public class Server implements Runnable  {

public final static String ADDRESS = "192.168.2.14";

public final static int PORT = 8511;

public final static long TIMEOUT = 10000;

public int clients;

ByteBuffer readBuffer = ByteBuffer.allocate(1024);

private ServerSocketChannel serverChannel;

private Selector selector;

private Map<SocketChannel,byte[]> dataTracking = new HashMap<SocketChannel, byte[]>();

public Server(){
    init();
}

private void init(){
    System.out.println("initializing server");

    if (selector != null) return;
    if (serverChannel != null) return;

    try {
        selector = Selector.open();
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.socket().bind(new InetSocketAddress(ADDRESS, PORT));
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void run() {
    System.out.println("Now accepting connections...");
    try{
        while (!Thread.currentThread().isInterrupted()){

            int ready = selector.select();
            if(ready==0)
                continue;
            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();

            while (keys.hasNext()){
                SelectionKey key = keys.next();
                keys.remove();
                if (!key.isValid()){
                    continue;
                }

                if (key.isAcceptable()){
                    System.out.println("Accepting connection");
                    accept(key);
                }

                if (key.isWritable()){
                    System.out.println("Writing...");
                    write(key);
                }

                if (key.isReadable()){
                    System.out.println("Reading connection");
                    read(key);
                }
            }
        }
    } catch (IOException e){
        e.printStackTrace();
    } finally{
        closeConnection();
    }

}

private void write(SelectionKey key) throws IOException{

    SocketChannel channel = (SocketChannel) key.channel();
    byte[] data = dataTracking.get(channel);
    dataTracking.remove(channel);
    **int count = channel.write(ByteBuffer.wrap(data));
    if(count == 0)
    {
        key.interestOps(SelectionKey.OP_WRITE);
        return;
    }
    else if(count > 0)
    {
        key.interestOps(0);
        key.interestOps(SelectionKey.OP_READ);  
    }** 
}

private void closeConnection(){

    System.out.println("Closing server down");
    if (selector != null){
        try {
            selector.close();
            serverChannel.socket().close();
            serverChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void accept(SelectionKey key) throws IOException{
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
    SocketChannel socketChannel = serverSocketChannel.accept();
    if(socketChannel == null)
    {
        throw new IOException();
    }
    socketChannel.configureBlocking(false);
     clients++;
    **//socketChannel.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
    SelectionKey skey = socketChannel.register(selector, SelectionKey.OP_READ);**

    byte[] hello = new String("Hello from server").getBytes();
    dataTracking.put(socketChannel, hello);
}

private void read(SelectionKey key) throws IOException{
    SocketChannel channel = (SocketChannel) key.channel();
    readBuffer.clear();
    int length;
    try {
        length = channel.read(readBuffer);
    } catch (IOException e) {
        System.out.println("Reading problem, closing connection");
        System.out.println("No of clients :"+clients);
        key.cancel();
        channel.close();
        return;
    }
    if (length == -1){
        System.out.println("Nothing was there to be read, closing connection");
        channel.close();
        key.cancel();
        return;
    }

    readBuffer.flip();
    byte[] data = new byte[1000];
    readBuffer.get(data, 0, length);
    String fromclient = new String(data,0,length,"UTF-8");
    System.out.println("Received: "+fromclient);
    String dat = fromclient+channel.getRemoteAddress();
    data= dat.getBytes();
    echo(key,data);
}

private void echo(SelectionKey key, byte[] data) throws IOException{
    SocketChannel socketChannel = (SocketChannel) key.channel();
    dataTracking.put(socketChannel, data);
    **//key.interestOps(SelectionKey.OP_WRITE);
    try
    {
        write(key);
    }
    catch(IOException e)
    {
        System.out.println("Problem in echo"+e);
        e.printStackTrace();
    }
}
public static void main(String [] args)
{
    Thread serv = new Thread(new Server());
    serv.start();
}

}

questionAnswers(1)

yourAnswerToTheQuestion