Search code examples
javamultithreadingudpdatagram

DatagramChannel packet listener taking high CPU


I have a packet Listener Thread in Java for UDP packets along with 2-3 other threads.

It was running fine till today but now the process javaw.exe has started using CONSTANT 50% CPU.

Here is my code.

public class PacketListenerThread implements Runnable {
    private SocketAddress receivedSocketAddress;
    private DatagramChannel channel;
    private ExecutorService pool;

    public PacketListenerThread(DatagramChannel channel, ExecutorService pool) {
        this.channel = channel;
        this.pool = pool;
    }

    @Override
    public void run() {
        while (true) {
            receivedSocketAddress = null;
            ByteBuffer recvbuf = ByteBuffer.allocate(1400);
            recvbuf.clear();
            try {
                receivedSocketAddress = channel.receive(recvbuf);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (receivedSocketAddress != null) {
                pool.submit(new PacketHandlerRunnable(new TaskObject(receivedSocketAddress, recvbuf)));
            }
        }
    }
}

I have stopped all other threads but this thread still uses "CONSTANT" 50% CPU .


Solution

  • See Javadoc:

    If a datagram is immediately available, or if this channel is in blocking mode and one eventually becomes available, then the datagram is copied into the given byte buffer and its source address is returned. If this channel is in non-blocking mode and a datagram is not immediately available then this method immediately returns null.

    Maybe your call to channel.receive(recvbuf) does not block, so you are looping at inifite speed which explains your CPU load.