等待线程将永远等待Java InetAddress.getByName(String)

时间:2015-02-27 07:33:11

标签: java multithreading wait inetaddress

由于以下代码段中的同步部分的组织方式,我遇到一些线程一直在等待。

lookupTable.wait(); 位于 synchronized(lookupTable)内, lookupTable.notifyAll(); 也是。虽然不可能在一个线程等待时,另一个线程可以发送 notifyAll()以停止等待。

这是来自java.net包中的InetAddress类的代码片段,并且在大约100个线程经常调用InetAddress.getByName(String)时执行。我试图将一堆主机名转换成相应的IP地址。

任何人都有同样的经历吗? 欢迎任何建议。

谢谢!

    private static InetAddress[] checkLookupTable(String host) {
        **synchronized (lookupTable)** {
            // If the host isn't in the lookupTable, add it in the
            // lookuptable and return null. The caller should do
            // the lookup.
            if (lookupTable.containsKey(host) == false) {
                lookupTable.put(host, null);
                return null;
            }

            // If the host is in the lookupTable, it means that another
            // thread is trying to look up the addresses of this host.
            // This thread should wait.
            while (lookupTable.containsKey(host)) {
                try {
                    **lookupTable.wait();**
                } catch (InterruptedException e) {
                }
            }
        }

        // The other thread has finished looking up the addresses of
        // the host. This thread should retry to get the addresses
        // from the addressCache. If it doesn't get the addresses from
        // the cache, it will try to look up the addresses itself.
        InetAddress[] addresses = getCachedAddresses(host);
        if (addresses == null) {
            synchronized (lookupTable) {
                lookupTable.put(host, null);
                return null;
            }
        }

        return addresses;
    }

    private static void updateLookupTable(String host) {
        **synchronized (lookupTable)** {
            lookupTable.remove(host);
            **lookupTable.notifyAll();**
        }
    }

0 个答案:

没有答案