views:

53

answers:

2

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");
      }
   }

}
A: 

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.

Maurice Perry
Bryan
I typed something in the console and pressed enter and I do see the opened message. However I have just discovered that if I use Scanner instead of BufferedReader it works without me typing anything. Odd
Yeah, that's odd
Maurice Perry