ServerSocket blocked by thread seeking input from

2019-07-23 17:23发布

问题:

Can anyone give me insight into why the ServerSocket constructor never returns in the new thread? (I never see the "Opened" message printed to the console.) It seems the main thread prevents the server socket thread from running by entering into readLine too quickly:

public class Main
{
   public static void main(String[] args) throws IOException
   {
      new Thread(new SocketOpener()).start();

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String inLine = br.readLine();
      System.out.println(inLine);
   }
}

public class SocketOpener implements Runnable
{

   public void run()
   {
      try
      {
         System.out.println("Opening...");
         ServerSocket socket = new ServerSocket(4444);
         System.out.println("Opened");
      }
      catch (IOException ex)
      {
         System.out.println("IO Error");
      }
   }

}

回答1:

I don't think that it's the ServerSocket constructor that blocks, but the System.out.println("Opened"). The fact that the main thread is trying to read from System.in prevents outputs to be done on System.out.



回答2:

Reading from System.in causes a lot of problems: Under some circumstances you can't:

  1. Create a Temp-File (because of 2)
  2. Read the Inet4Adress of your maschine
  3. Load a DLL

I've encountert some of this Problems with Windows Server 2003 and older. This happens because of some Bugs in the Win32-API ans Java-VM.

But there may be an easy workarround:

Only call System.in.read(), if System.in.availiable() returns a value larger than 0.

  • Deadlock between System.loadLibrary() and System.in.read()
  • Inet4AddressImpl.getLocalHostName is hanging intermittenly
  • Deadlock in Win32