class Selenium::WebDriver::SocketLock

def can_lock?

def can_lock?
  @server = TCPServer.new(Platform.localhost, @port)
  @server.close_on_exec = true
  true
rescue SocketError, Errno::EADDRINUSE, Errno::EBADF => e
  WebDriver.logger.debug("#{self}: #{e.message}", id: :driver_service)
  false
end

def current_time

def current_time
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

def did_lock?

def did_lock?
  !@server.nil?
end

def initialize(port, timeout)

def initialize(port, timeout)
  @port    = port
  @server  = nil
  @timeout = timeout
end

def lock

def lock
  max_time = current_time + @timeout
  sleep 0.1 until can_lock? || current_time >= max_time
  return if did_lock?
  raise Error::WebDriverError, "unable to bind to locking port #{@port} within #{@timeout} seconds"
end

def locked

def locked
  lock
  begin
    yield
  ensure
    release
  end
end

def release

def release
  @server&.close
end