简体   繁体   中英

Java off-heap memory leak in program checking for IPv6 network interface

I have a network client which repeatedly performs an action which is slightly different depending on whether the client machine has IPv6 on a non-loopback interface:

public void doTheThing() throws SocketException {
    while (true) {
        if (hasIPv6Address(NetworkInterface.getNetworkInterfaces())) {
            doTheIPv6Thing();
        } else {
            doTheIPv4Thing();
        }
    }
}

private static boolean hasIPv6Address(Enumeration<NetworkInterface> intfs) throws SocketException {
    while (intfs.hasMoreElements()) {
        NetworkInterface intf = intfs.nextElement();
        if (intf.isLoopback()) continue;
        Enumeration<InetAddress> addresses = intf.getInetAddresses();
        while (addresses.hasMoreElements()) {
            if (addresses.nextElement() instanceof Inet6Address) return true;
        }
        if (hasIPv6Address(intf.getSubInterfaces())) return true;
    }
    return false;
}

This program has a strange off-heap memory leak: the Java heap is stable, and the number of threads is stable, but the memory use still grows and grows until the program is killed by the oom-killer. Why?

This is a known bug in Java with NetworkInterface.isLoopback() . It is fixed in Java 7 (u60) and Java 8 (b105) and will not be fixed in Java 6.

Probably, my client doesn't really need to check whether an IPv6 interface has suddenly appeared or disappeared, and can just check once at the beginning instead of at every iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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