Permalink
Browse files

Look for next free port if once chosen is busy

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...
1 parent 632ea16 commit ada4d396e0b4891c40f129ef6d3ea57b59854ec2 @avsej avsej committed with ingenthr Jun 7, 2012
Showing with 16 additions and 6 deletions.
  1. +16 −6 src/main/java/org/couchbase/mock/CouchbaseMock.java
@@ -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;
@@ -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);
@@ -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);
}
}

0 comments on commit ada4d39

Please sign in to comment.