2323import java .net .Socket ;
2424import java .util .HashMap ;
2525import java .util .Map ;
26+ import java .util .concurrent .CountDownLatch ;
27+ import java .util .concurrent .TimeUnit ;
2628
2729/**
2830 * @author Scott Battaglia
@@ -43,6 +45,8 @@ public final class PublicTestHttpServer extends Thread {
4345
4446 private ServerSocket server ;
4547
48+ private final CountDownLatch ready = new CountDownLatch (1 );
49+
4650 private static Map <Integer , PublicTestHttpServer > serverMap = new HashMap <Integer , PublicTestHttpServer >();
4751
4852 private PublicTestHttpServer (String data , String encoding , String MIMEType , int port )
@@ -61,20 +65,31 @@ private PublicTestHttpServer(byte[] data, String encoding, String MIMEType, int
6165
6266 public static synchronized PublicTestHttpServer instance (final int port ) {
6367 if (serverMap .containsKey (port )) {
64- return serverMap .get (port );
68+ PublicTestHttpServer server = serverMap .get (port );
69+ server .waitUntilReady ();
70+ return server ;
6571 }
6672
6773 try {
6874 final PublicTestHttpServer server = new PublicTestHttpServer ("test" , "ASCII" , "text/plain" , port );
6975 server .start ();
7076 serverMap .put (port , server );
71- Thread . yield ();
77+ server . waitUntilReady ();
7278 return server ;
7379 } catch (Exception e ) {
7480 throw new RuntimeException (e );
7581 }
7682 }
7783
84+ private void waitUntilReady () {
85+ try {
86+ ready .await (10 , TimeUnit .SECONDS );
87+ } catch (InterruptedException e ) {
88+ Thread .currentThread ().interrupt ();
89+ throw new RuntimeException ("interrupted" , e );
90+ }
91+ }
92+
7893 public void shutdown () {
7994 System .out .println ("Shutting down connection on port " + server .getLocalPort ());
8095 try {
@@ -91,6 +106,7 @@ public void run() {
91106 try {
92107 this .server = new ServerSocket (this .port );
93108 System .out .println ("Accepting connections on port " + server .getLocalPort ());
109+ notifyReady ();
94110 while (true ) {
95111
96112 Socket connection = null ;
@@ -131,4 +147,8 @@ public void run() {
131147 }
132148
133149 } // end run
150+
151+ private void notifyReady () {
152+ ready .countDown ();
153+ }
134154}
0 commit comments