title: If a ServerSocket is garbage-collected, what happens to its associated port binding?
body: <p>I want to create an application that can detect other instances of itself and prevent them from running.  To accomplish this, I'm thinking of opening up a new <code>ServerSocket</code> on some application-specific port, and then relying on the exception that should be thrown if I try to bind to the same port more than once to "detect" and kill duplicate application instances.  I know I could do something like write a file into the present-working-directory and "detect" it to accomplish the same sort of behavior, but I really don't want to do this (what happens if the app dies and can't remove the file?), so that's why I've chosen the <code>ServerSocket</code> route.</p>
  
  <p>Let's say I have the following code:</p>
  
  <pre><code>public class MyClass{
      public static void main(String[] args) throws IOException{
          new ServerSocket(1234);
  
          new Thread(){
              //This is a non-daemon thread. Assume its run() method never returns.
          }.start();
      }
  }
  </code></pre>
  
  <p><strong>Question</strong></p>
  
  <p>Short of creating the <code>ServerSocket</code>, my application never really needs to use it again, because its mere existence allows me to detect when another instance of my app attempts to start up.  Thus, saving a reference to said <code>ServerSocket</code> will result in a compile warning (unused reference).  I'm a neat-freak, so I'd rather not save a reference if I can avoid it.  My question is, will this <code>ServerSocket</code> instance get garbage collected before all non-daemon threads exit (assuming the app doesn't fail or exit some other way), and if so, will its associated port become unbound as a result?</p>