My server fails with java.net.SocketException: Too many files open
Network sockets are treated like files and your operating system has a limit to the number of file handles it can manage. Running out of file handles is usually due to a large number of clients connecting and disconnecting frequently. As specified by TCP, after being closed sockets remain in the TIME_WAIT state for some additional time. The reason is to ensure that delayed packets arrive on the correct socket. In Windows, the default TIME_WAIT timeout is 4 minutes, in Linux it is 60 seconds.
Change the timeout in Windows
- Run regedit to start the Registry Editor
- Locate the following key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\tcpip\Parameters
- Add a new value named TcpTimedWaitDelay asa decimal and set the desired timeout in seconds (30-300)
- Reboot
Change the timeout in Linux
Update the configuration value by running (30 seconds used in the example)
echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout
Restart the networking component, for example by running
/etc/init.d/networking restart
or
service network restart