code: private void removeExpiredQueries()
      {
          DateTime timeHorizon = DateTime.now().minus(minQueryExpireAge.toMillis());
  
          // we're willing to keep queries beyond timeHorizon as long as we have fewer than maxQueryHistory
          while (expirationQueue.size() > maxQueryHistory) {
              T query = expirationQueue.peek();
              if (query == null) {
                  return;
              }
  
              // expirationQueue is FIFO based on query end time. Stop when we see the
              // first query that's too young to expire
              Optional<DateTime> endTime = query.getEndTime();
              if (!endTime.isPresent()) {
                  // this shouldn't happen but it is better to be safe here
                  continue;
              }
              if (endTime.get().isAfter(timeHorizon)) {
                  return;
              }
  
              // only expire them if they are older than minQueryExpireAge. We need to keep them
              // around for a while in case clients come back asking for status
              QueryId queryId = query.getQueryId();
  
              log.debug("Remove query %s", queryId);
              queries.remove(queryId);
              expirationQueue.remove(query);
          }
      }
docs: Remove completed queries after a waiting period