Class PortAllocationService

java.lang.Object
org.jenkinsci.gradle.plugins.jpi2.PortAllocationService
All Implemented Interfaces:
AutoCloseable, org.gradle.api.services.BuildService<org.gradle.api.services.BuildServiceParameters.None>

public abstract class PortAllocationService extends Object implements org.gradle.api.services.BuildService<org.gradle.api.services.BuildServiceParameters.None>, AutoCloseable
A shared Gradle build service that finds and reserves free TCP ports for use during the build, e.g. the Jenkins server port for testServer/testHplRun.

reservePort() keeps the underlying ServerSocket open so the reservation is actually held: the OS cannot hand the same port to another concurrent reservation from this build (e.g. a sibling module's testServer task running in parallel) while it is outstanding. Callers must release it with releasePort(int) once they are done with the number -- typically right before spawning the process that will actually bind it, since the socket can't be held open across that handoff. Any reservation a caller forgets to release is closed when the build service itself is closed at the end of the build.

  • Constructor Details

    • PortAllocationService

      public PortAllocationService()
  • Method Details

    • reservePort

      public int reservePort()
      Reserves a free port, holding it open until releasePort(int) is called.
      Returns:
      a reserved port number
      Throws:
      IllegalStateException - if no free port can be found after retrying
    • releasePort

      public void releasePort(int port)
      Releases a port previously obtained from reservePort(), closing the socket that was holding it open. Safe to call more than once, or with a port that was never reserved -- both are no-ops.
      Parameters:
      port - The port to release
    • findAndReserveFreePort

      public int findAndReserveFreePort()
      Finds a free port and releases it again before returning, for callers that don't hold a long-lived reservation. Because the socket is closed before this method returns, the port can be claimed by anything else on the machine before the caller gets around to using it; prefer reservePort() paired with releasePort(int) kept open across the handoff to another process, which closes that window as much as a TCP port reservation can.
      Returns:
      a free port number
      Throws:
      IllegalStateException - if no free port can be found after retrying
    • close

      public void close()
      Closes any reservations that were never explicitly released, so a caller that fails between reservePort() and releasePort(int) doesn't leak an open socket for the rest of the build. Called automatically by Gradle when the build service is closed.
      Specified by:
      close in interface AutoCloseable