Java异步套接字多线程性能

时间:2011-10-30 12:13:02

标签: java multithreading asynchronous

我需要询问11M名称服务器并找出它们中的哪些存活。在Java中,我使用异步套接字发送udp请求,一切正常,直到我尝试使用多个线程。虽然我使用了高性能的16核集群,但速度会按比例上升,但积极响应会急剧下降。 我为每个线程创建一个单独的通道,并没有明显的原因发生这种情况。任何人都可以解释我做错了什么,是否可以在线程中使用不同的异步套接字?

这是一些代码。所以我有很多带有id的线程和它的主机列表,每个主机都执行以下操作:

@Override
public void run() {
    DatagramChannel channel = null;
    try {
        channel = DatagramChannel.open();
        InetSocketAddress isa = new InetSocketAddress(Settings.LOCAL_PORT+id);
        channel.socket().bind(isa);
        channel.configureBlocking(false);
        Selector selector = Selector.open(); 
        channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        ByteBuffer outBuffer = ByteBuffer.wrap(Settings.QUERY);
        ByteBuffer inBuffer = ByteBuffer.allocate(200);
        while (true) {          
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {                
                SelectionKey key = iterator.next();
                iterator.remove();
                if (!key.isValid()) {
                    continue;
                }
                if (key.isReadable()) {
                    inBuffer.clear();
                    channel.receive(inBuffer);
                    inBuffer.flip();
                    inCounter++;
                    //some analize of response
                    continue;
                }
                if (key.isWritable()) {
                    if (outCounter < hosts.size()) {
                        channel.send(outBuffer, new InetSocketAddress(hosts.get(outCounter), Settings.DNS_PORT));
                        outBuffer.flip();
                        outCounter++;
                    } 
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (channel != null)
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }                       
        }

    }
}

1 个答案:

答案 0 :(得分:0)

由于UDP是一种不可靠的协议,因此必须注意不要使系统过载,否则网络缓冲区或数据包将丢失。如何做到这一点很可能对许多因素都很敏感,所以我这样做有点不同可能会提高你的回复率。

您使用的是UDP数据报还是TCP套接字?为什么要尝试调查1100万台名称服务器?

相关问题