title: When sockets are dereferenced, are they garbage collected
body: <p>I am trying to understand the concept of SO_TIMEOUT, threads resources and garbage collection.</p>
  
  <p>I have seen a coding bug in my project where a set are sockets are wrongly dereferenced without closing.</p>
  
  <p>And they get closed within few minutes with JAVA 1.6 but with JAVA 1.8 they take hours to close. [tested only on linux platform]</p>
  
  <p>So I want to dig deeper into the issue.</p>
  
  <p>I created this program in which I create 10 sockets but as you can see that 9 of them are derefernced and then the thread goes to long sleep duration:</p>
  
  <pre><code>    import java.net.Socket;
  
  /**
   * Created by 212477559 on 5/30/16.
   */
  public class TestClientSocket {
  
      public static void main(String args[])
      {
          try
          {
              Socket socket;
              for(int j=0;j&lt;10;j++)
              {
                  socket =new Socket("localhost",9090);
                  socket.setKeepAlive(false);
              }
  
  
              Thread.sleep(900000);
  
          }
         catch(Exception e)
          {
              System.out.println("throws");
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>Now when I run </p>
  
  <blockquote>
    <p>netstat -np TCP | find "9090"</p>
  </blockquote>
  
  <p>I can still see that after half an hour or so all sockets are still in established state. So I have following questions :</p>
  
  <p>1) why those 9 sockets are not garbage collected?</p>
  
  <p>2) is that thread still holding the resources?</p>
  
  <p>3) are the below mentioned ways the only ways to close the sockets:</p>
  
  <pre><code>   1. close the sockets?
     2. Thread which created those sockets must exit?
     3. SO_TIMEOUT should expire?
  </code></pre>