简体   繁体   English

DatagramChannel数据包监听器占用高CPU

[英]DatagramChannel packet listener taking high CPU

I have a packet Listener Thread in Java for UDP packets along with 2-3 other threads. 我有一个用于UDP数据包的Java数据包侦听器线程以及2-3个其他线程。

It was running fine till today but now the process javaw.exe has started using CONSTANT 50% CPU. 它一直运行到今天,但现在进程javaw.exe已经开始使用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 . 我已经停止了所有其他线程但这个线程仍然使用“CONSTANT”50%CPU。

See Javadoc : 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. 如果此通道处于非阻塞模式且数据报不能立即可用,则此方法立即返回null。

Maybe your call to channel.receive(recvbuf) does not block, so you are looping at inifite speed which explains your CPU load. 也许你对channel.receive(recvbuf)的调用没有阻塞,所以你以无限速度循环,这解释了你的CPU负载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM