How I can reduce run time of this code?

时间:2016-04-04 20:58:00

标签: java

InetAddress localhost = null;
try {
    localhost = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
    /* Purposely empty */
}

byte[] ip = localhost.getAddress();
int i = 1;
while (i <= 254) {
    ip[3] = (byte) i;
    InetAddress address = null;
    try {
        address = InetAddress.getByAddress(ip);
    } catch (UnknownHostException ex) {
        /* Purposely empty */
    }

    String HostName = address.getHostName();
    if (!address.getHostAddress().equals(address.getHostName())) {
        list.addElement(HostName);
    }
    i++;
}

(I have problem is long the run time. How I can reduce the run time in this code)

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,涉及IP地址的网络查找。网络延迟问题就像其他人一样#34;说...它是由网络驱动的。到达目的地需要多长时间和多少跳。

我找到的唯一解决方案就是在您的情况下将查找,InetAddress.getByAddress(ip)线程化。我的解决方案是设置一个包含10个线程的ExecutorService。将每个InetAddress.getByAddress(ip)打包到Callable中。监视Callable以完成。打包另一个并启动它。看看我在这个论坛上与此问题相关的一个问题:

ExecutorService - How to set values in a Runnable/Callable and reuse

对ExecutorService保持谨慎(我发现)。线程数实际上取决于运行时硬件的CPU数(Power)。太多的线程,它会停下来(相信我)。线程太少,你的时间减少可能无法达到。

我离开了我公司的部门,在那里我实施了最终的解决方案,所以我没有现成的代码。但是上面的链接提供了ExecutorService和使用Callable对象的一些基本代码。