Skip to content

Commit

Permalink
Look for next free port if once chosen is busy
Browse files Browse the repository at this point in the history
This fixes spontaneous java.net.BindException like this one:

Jun 7, 2012 4:41:45 PM org.couchbase.mock.CouchbaseMock start
SEVERE: null
java.net.BindException: Address already in use
    at sun.nio.ch.Net.bind(Native Method)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:137)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:77)
    at sun.net.httpserver.ServerImpl.<init>(ServerImpl.java:88)
    at sun.net.httpserver.HttpServerImpl.<init>(HttpServerImpl.java:50)
    at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(DefaultHttpServerProvider.java:35)
    at com.sun.net.httpserver.HttpServer.create(HttpServer.java:129)
    at org.couchbase.mock.CouchbaseMock.start(CouchbaseMock.java:374)
    at org.couchbase.mock.CouchbaseMock.main(CouchbaseMock.java:322)

Change-Id: I687a12dd04d1cc4cd9c204bdeebc0159f358aabe
Reviewed-on: http://review.couchbase.org/16981
Tested-by: Sergey Avseyev <sergey.avseyev@gmail.com>
Reviewed-by: Matt Ingenthron <matt@couchbase.com>
  • Loading branch information
avsej authored and ingenthr committed Jun 8, 2012
1 parent 632ea16 commit ada4d39
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/main/java/org/couchbase/mock/CouchbaseMock.java
Expand Up @@ -24,6 +24,7 @@
import java.util.logging.Logger;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
Expand Down Expand Up @@ -307,11 +308,6 @@ public static void main(String[] args) {
}

try {
if (port == 0) {
ServerSocket server = new ServerSocket(0);
port = server.getLocalPort();
server.close();
}
CouchbaseMock mock = new CouchbaseMock(hostname, port, nodes, vbuckets, bucketsSpec);
if (harakirimonitor != null) {
mock.setupHarakiriMonitor(harakirimonitor, true);
Expand Down Expand Up @@ -368,13 +364,27 @@ public void start() {
}

try {
httpServer = HttpServer.create(new InetSocketAddress(port), 10);
boolean busy = true;
do {
if (port == 0) {
ServerSocket server = new ServerSocket(0);
port = server.getLocalPort();
server.close();
}
try {
httpServer = HttpServer.create(new InetSocketAddress(port), 10);
} catch (BindException ex) {
System.err.println("Looks like port " + port + " busy, lets try another one");
}
busy = false;
} while (busy);
httpServer.createContext("/pools", new PoolsHandler(this)).setAuthenticator(authenticator);
httpServer.setExecutor(Executors.newCachedThreadPool());
httpServer.start();
startupLatch.countDown();
} catch (IOException ex) {
Logger.getLogger(CouchbaseMock.class.getName()).log(Level.SEVERE, null, ex);
System.exit(-1);
}

}
Expand Down

0 comments on commit ada4d39

Please sign in to comment.