Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

java - High CPU usage for UDP server

I'm working on a simple UDP server. To receive packets I created a Thread subclass and in its run() method I have the following infinite loop:

val buffer = ByteBuffer.allocate(Packet.MAX_PACKET_SIZE)

while (continueRunning) {
    buffer.clear()
    val address = socket.receive(buffer) // DatagramChannel in non-blocking mode
    buffer.flip()
 
    // No packets received, always null
    if (address != null) {
        val data = ByteArray(buffer.limit())
        buffer.get(data, 0, buffer.limit())
        val packet = DatagramPacket(data, data.size, address)

        // threadPool is created with Executors.newCachedThreadPool()
        threadPool.submit { packetProcessor.processPacket(packet) }
    }
 
    val answer = answerQueue.poll() // ConcurrentLinkedQueue

    // Answer queue is always empty, so this is always null as well
    if (answer != null) socket.send(ByteBuffer.wrap(answer.data), answer.socketAddress)
}

After calling start() function for this thread the application's CPU usage jumps to 15 - 25% and stays at this value while the thread is not stopped. I am actually okay with it. But I wonder if it is a normal situation when the server takes a lot of CPU time while doing nothing except of running an infinite loop? Or should I use some tricks to lower the CPU usage? And if I should, what should I do?

question from:https://stackoverflow.com/questions/66061932/high-cpu-usage-for-udp-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...