使用JAVA从套接字读取时减少CPU开销

时间:2013-04-12 07:56:32

标签: java multithreading sockets

我有两个线程会增加CPU开销。 1.以同步方式从套接字读取。 2.等待接受其他客户的联系

问题1,我只是试图读取来自客户端的任何数据,并且我不能使用readline,因为传入的数据具有我标记为知道消息标题末尾的换行符。所以我在一个线程中使用这种方式,但它增加了CPU开销

 public static String convertStreamToString(TCPServerConnectionListner socket) throws UnsupportedEncodingException, IOException, InterruptedException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getSocket().getInputStream()));
        // At this point it is too early to read. So it most likely return false
        System.out.println("Buffer Reader ready? " + reader.ready());
        // StringBuilder to hold the response
        StringBuilder sb = new StringBuilder();
        // Indicator to show if we have started to receive data or not
        boolean dataStreamStarted = false;
        // How many times we went to sleep waiting for data
        int sleepCounter = 0;
        // How many times (max) we will sleep before bailing out
        int sleepMaxCounter = 5;
        // Sleep max counter after data started
        int sleepMaxDataCounter = 50;
        // How long to sleep for each cycle
        int sleepTime = 5;
        // Start time
        long startTime = System.currentTimeMillis();
        // This is a tight loop. Not sure what it will do to CPU
        while (true) {
            if (reader.ready()) {
                sb.append((char) reader.read());
                // Once started we do not expect server to stop in the middle and restart
                dataStreamStarted = true;
            } else {
                Thread.sleep(sleepTime);
                if (dataStreamStarted && (sleepCounter >= sleepMaxDataCounter)) {
                    System.out.println("Reached max sleep time of " + (sleepMaxDataCounter * sleepTime) + " ms after data started");
                    break;
                } else {
                    if (sleepCounter >= sleepMaxCounter) {
                        System.out.println("Reached max sleep time of " + (sleepMaxCounter * sleepTime) + " ms. Bailing out");
                        // Reached max timeout waiting for data. Bail..
                        break;
                    }
                }
                sleepCounter++;
            }

        }
        long endTime = System.currentTimeMillis();

        System.out.println(sb.toString());
        System.out.println("Time " + (endTime - startTime));

        return sb.toString();
    }

问题2,我不知道这样做的最佳方式是什么,我只是有一个不断等待其他客户端的线程,并接受它。但这也需要很多CPU开销。

 // Listner to accept any client connection
    @Override
    public void run() {

        while (true) {
            try {
                mutex.acquire();
                if (!welcomeSocket.isClosed()) {
                    connectionSocket = welcomeSocket.accept();
                   // Thread.sleep(5);
                }


            } catch (IOException ex) {
                Logger.getLogger(TCPServerConnectionListner.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InterruptedException ex) {
                Logger.getLogger(TCPServerConnectionListner.class.getName()).log(Level.SEVERE, null, ex);
            }
            finally
            {
                mutex.release();
            }

        }
    }
}

Profiler图片也会有所帮助,但我想知道为什么SwingWorker线程花了那么多时间?  enter image description here

更新问题一的代码:

    public static String convertStreamToString(TCPServerConnectionListner socket) throws UnsupportedEncodingException, IOException, InterruptedException {

            byte[] resultBuff = new byte[0];
            byte[] buff = new byte[65534];
            int k = -1;
            k = socket.getSocket().getInputStream().read(buff, 0, buff.length);
                byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read
                System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes
                System.arraycopy(buff, 0, tbuff, resultBuff.length, k);  // copy current lot
                resultBuff = tbuff; // call the temp buffer as your result buff

        return new String(resultBuff);
    }

}
        ![snapshot][2]

3 个答案:

答案 0 :(得分:2)

只是摆脱ready()调用和阻止。你准备好的所有事情()都是假的,实际上是完全浪费时间,包括睡觉。 read()将完全阻止正确的时间。 sleep()赢了{{1}}。你要么睡不好,要么浪费CPU时间,要么太长,这会增加延迟。有一段时间你可能会睡觉正确的时间,但这是100%的运气,而不是良好的管理。如果您想要读取超时,请使用读取超时。

答案 1 :(得分:1)

您似乎在等待一段时间后没有更多数据。

我建议您使用Socket.setSoTimeout(timeout in seconds)

更好的解决方案是不需要通过一个允许您知道何时到达数据结束的协议来实现此目的。如果您的服务器实施不当而您无法解决问题,则只能执行此操作。

答案 2 :(得分:0)

问题1. 100%CPU可能是因为您正在从BufferedReader.read()中读取单个字符。相反,您可以将数据块读取到数组并将其添加到您的stringbuilder中。