package jugsaar12.nio.networking;

import java.io.IOException;
import java.net.Socket;

/**
 * sysctl kern.num_threads
 */
public class SocketGrabber {

    public static void main(String[] args) throws Exception {

        for (int i = 0; i < 20000; i++) {
            try {
                new Socket("localhost", 1337).getOutputStream().write('H');
                System.out.printf("Socket: %s%n", i);
            } catch (IOException e) {
                System.err.printf("Could not connect - %s%n", e);
            }
        }
    }
}
@@ -146,20 +146,17 @@
 bber %7B%0A%0A
-    
+%09
 public s
@@ -206,24 +206,18 @@
 tion %7B%0A%0A
-        
+%09%09
 for (int
@@ -246,118 +246,330 @@
 ) %7B%0A
-            try %7B%0A                new Socket(%22localhost%22, 1337).getOutputStream().write('H');%0A                
+%09%09%09try %7B%0A%09%09%09%09try (Socket socket = new Socket(%22localhost%22, 1337)) %7B%0A%0A%09%09%09%09%09//allow reuse socket address and ensure that the socket doesn't stay around for too long.%0A%09%09%09%09%09socket.setReuseAddress(true);%0A%09%09%09%09%09socket.setSoLinger(true, 0);%0A%0A%09%09%09%09%09socket.getOutputStream().write('H');%0A%09%09%09%09%09socket.getInputStream().read();%0A%09%09%09%09%7D%0A%09%09%09%09
 Syst
@@ -602,28 +602,19 @@
 n%22, i);%0A
-            
+%09%09%09
 %7D catch 
@@ -635,24 +635,12 @@
 ) %7B%0A
-                
+%09%09%09%09
 Syst
@@ -689,35 +689,17 @@
 e);%0A
-            %7D%0A        %7D%0A    
+%09%09%09%7D%0A%09%09%7D%0A%09
 %7D%0A%7D

Make sure SocketGrabber releases sockets early.