@@ -369,26 +369,50 @@ protected void prepare() throws Exception {
369
369
port = Integer .parseInt (debug );
370
370
}
371
371
}
372
+ int originalPort = port ;
372
373
if (port <= 0 ) {
373
374
port = getRandomPort ();
374
375
}
375
376
376
377
if (debug != null && debug .equalsIgnoreCase ("client" )) {
377
378
args .add ("-agentlib:jdwp=transport=dt_socket,address=" + debugHost + ":" + port + ",server=n,suspend=" + suspend );
378
379
} else if (debug == null || !debug .equalsIgnoreCase ("false" )) {
379
- // make sure the debug port is not used, we don't want to just fail if something else is using it
380
- // we don't check this on restarts, as the previous process is still running
380
+ // if the debug port is used, we want to make an effort to pick another one
381
+ // if we can't find an open port, we don't fail the process launch, we just don't enable debugging
382
+ // Furthermore, we don't check this on restarts, as the previous process is still running
383
+ boolean warnAboutChange = false ;
381
384
if (debugPortOk == null ) {
382
- try (Socket socket = new Socket (getInetAddress (debugHost ), port )) {
383
- error ("Port " + port + " in use, not starting in debug mode" );
384
- debugPortOk = false ;
385
- } catch (IOException e ) {
386
- debugPortOk = true ;
385
+ int tries = 0 ;
386
+ while (true ) {
387
+ boolean isPortUsed ;
388
+ try (Socket socket = new Socket (getInetAddress (debugHost ), port )) {
389
+ // we can make a connection, that means the port is in use
390
+ isPortUsed = true ;
391
+ warnAboutChange = warnAboutChange || (originalPort != 0 ); // we only want to warn if the user had not configured a random port
392
+ } catch (IOException e ) {
393
+ // no connection made, so the port is not in use
394
+ isPortUsed = false ;
395
+ }
396
+ if (!isPortUsed ) {
397
+ debugPortOk = true ;
398
+ break ;
399
+ }
400
+ if (++tries >= 5 ) {
401
+ debugPortOk = false ;
402
+ break ;
403
+ } else {
404
+ port = getRandomPort ();
405
+ }
387
406
}
388
407
}
389
408
if (debugPortOk ) {
409
+ if (warnAboutChange ) {
410
+ warn ("Changed debug port to " + port + " because of a port conflict" );
411
+ }
390
412
args .add ("-agentlib:jdwp=transport=dt_socket,address=" + debugHost + ":" + port + ",server=y,suspend="
391
413
+ suspend );
414
+ } else {
415
+ error ("Port " + port + " in use, not starting in debug mode" );
392
416
}
393
417
}
394
418
0 commit comments