0

NIO サーバーに接続するために以下のクライアント スレッドを使用しています。

    class RunnableDemo implements Runnable {
    private Thread t;
    private String threadName;

    InetAddress host = null;
    int port = 9090;

    RunnableDemo(String name) {
        threadName = name;
        System.err.println("Creating " + threadName);

    }

    public void run() {
        System.err.println("Running " + threadName);
        try {
            SocketChannel socketChannel = SocketChannel.open();

            socketChannel.configureBlocking(false);

            socketChannel.connect(new InetSocketAddress(host, port));

            while (!socketChannel.finishConnect())
                ;

            System.out.println("Thread " + threadName + " Connected");

            while (true) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                if (socketChannel.read(buffer) != 0) {
                    buffer.flip();
                    byte[] bytes = new byte[buffer.limit()];
                    buffer.get(bytes);
                    System.out.println(threadName+ ":" + new String(bytes));
                    buffer.clear();
                }
            }

        } catch (Exception e) {
            System.out.println("Thread " + threadName + " interrupted.");
            e.printStackTrace();
        }
        System.out.println("Thread " + threadName + " exiting.");
    }

    public void start() {
        System.out.println("Starting " + threadName);
        try {
            host = InetAddress.getByName("127.0.0.1");
            if (t == null) {
                t = new Thread(this, threadName);
                t.start();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

}

これは私のサーバー側のコードです。サーバー側のみを実行している場合、CPU は 5% 以下ですが、スレッドごとにクライアントを実行すると、CPU 使用率が約 20 ~ 30% 上昇します。

public class EchoServer {
    private static final int BUFFER_SIZE = 1024;

    private final static int DEFAULT_PORT = 9090;

    private long numMessages = 0;

    private long loopTime;

    private InetAddress hostAddress = null;

    private int port;

    private Selector selector;

    // The buffer into which we'll read data when it's available
    private ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE);

    int timestamp=0;

    public EchoServer() throws IOException {
        this(DEFAULT_PORT);
    }

    public EchoServer(int port) throws IOException {
        this.port = port;
        hostAddress = InetAddress.getByName("127.0.0.1");
        selector = initSelector();
        loop();
    }

    private Selector initSelector() throws IOException {
        Selector socketSelector = SelectorProvider.provider().openSelector();

        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);

        InetSocketAddress isa = new InetSocketAddress(hostAddress, port);
        serverChannel.socket().bind(isa);
        serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
        return socketSelector;
    }

    private void loop() {
        for (;true;) {
            try {
                selector.select();
                Iterator<SelectionKey> selectedKeys = selector.selectedKeys()
                        .iterator();
                while (selectedKeys.hasNext()) {
                    SelectionKey key = selectedKeys.next();
                    selectedKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                     // Check what event is available and deal with it
                    if (key.isAcceptable()) {
                        accept(key);

                    } else if (key.isWritable()) {
                        write(key);
                    }
                }
                Thread.sleep(3000);
                timestamp+=3;
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }



        }
    }

    private void accept(SelectionKey key) throws IOException {

        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
        socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);

        socketChannel.register(selector, SelectionKey.OP_WRITE);

        System.out.println("Client is connected");
    }

    private void write(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        ByteBuffer dummyResponse = ByteBuffer.wrap(("ok:" + String.valueOf(timestamp)) .getBytes("UTF-8"));

        socketChannel.write(dummyResponse);
        if (dummyResponse.remaining() > 0) {
            System.err.print("Filled UP");
        }
        System.out.println("Message Sent");
     //   key.interestOps(SelectionKey.OP_READ);
    }
}

すべてが正しく機能します。クライアントとサーバーはお互いを認識して通信できます。私のコードが受け入れることができる接続の量をテストするために、上記のスレッドのインスタンスをいくつか作成しましたが、ここに問題があります。

このスレッドの各インスタンスを生成してタスク パネル (Windows) のパフォーマンス セクターを追跡すると、PC (2.6 コアの i5 CPU を使用しています) の CPU 使用率が 30% 上昇し、3 つのスレッドを生成することで CPU 使用率は約100% !!!

私のCPUの30%を占める上記のコードの問題は何だろうと思っています。

4

2 に答える 2

2

CPU 負荷が高くなる潜在的な原因が 2 つあります。

  1. 非ブロッキング I/O を不適切に使用しています。(事実上) チャネルを繰り返しポーリングして接続を完了し、データを読み取ります。この特定のユース ケースでは、ブロッキング I/O を使用することをお勧めします。データのスループットは (ほぼ) 同じであり、ポーリングによって CPU を浪費することはありません。

    一般的に言えば、ノンブロッキング I/O は、スレッドがブロッキング以外の処理を行う場合にのみ有効です。

  2. への書き込みSystem.outもかなりの CPU を使用する可能性があります ... JVM の外部。標準出力が、それを画面に表示する典型的なコンソール アプリケーションに送られる場合、テキストを画面にレンダリングして描画するプロセスと、スクロールするプロセスで、かなりの量の CPU が使用される可能性があります。

于 2014-12-25T11:26:44.330 に答える