DatagramChannel数据包监听器占用高CPU

时间:2012-07-17 14:38:20

标签: java multithreading udp datagram

我在Java中有一个用于UDP数据包的数据包侦听器线程以及2-3个其他线程。

它一直运行到今天,但现在javaw.exe进程已经开始使用CONSTANT 50%CPU了。

这是我的代码。

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)));
            }
        }
    }
}

我已停止所有其他线程,但此线程仍然使用“CONSTANT”50%CPU。

1 个答案:

答案 0 :(得分:2)

请参阅Javadoc

  

如果数据报立即可用,或者此通道处于阻塞模式且最终可用,则将数据报复制到给定的字节缓冲区中并返回其源地址。如果此通道处于非阻塞模式且数据报不能立即可用,则此方法立即返回null。

也许你对channel.receive(recvbuf)的调用没有阻塞,所以你以无限速度循环,这解释了你的CPU负载。