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
  1. Run regedit to start the Registry Editor
  2. Locate the following key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\tcpip\Parameters
  3. Add a new value named TcpTimedWaitDelay asa decimal and set the desired timeout in seconds (30-300)
  4. Reboot
Change the timeout in Linux
  1. Update the configuration value by running (30 seconds used in the example)

    echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout

  2. Restart the networking component, for example by running

    /etc/init.d/networking restart

  3. or

    service network restart