Override complete(), completeExceptionally(), and cancel() to cancel the timeout task and remove the request from the map
164640
@Override
   public boolean complete(T value) {
      cancelTimeoutTask();
      repository.removeRequest(requestId);
      return super.complete(value);
   }
987826
def _do_cancel_problems(self):
        
        try:
            while True:
                # Pull as many problems as we can, block when none are available.

                # `None` task is used to signal thread termination
                item = self._cancel_queue.get()
                if item is None:
                    break

                item_list = [item]
                while True:
                    try:
                        item_list.append(self._cancel_queue.get_nowait())
                    except queue.Empty:
                        break

                # Submit the problems, attach the ids as a json list in the
                # body of the delete query.
                try:
                    body = [item[0] for item in item_list]

                    try:
                        self.session.delete(posixpath.join(self.endpoint, 'problems/'), json=body)
                    except requests.exceptions.Timeout:
                        raise RequestTimeout

                except Exception as err:
                    for _, future in item_list:
                        if future is not None:
                            future._set_error(err, sys.exc_info())

                # Mark all the ids as processed regardless of success or failure.
                [self._cancel_queue.task_done() for _ in item_list]

                # this is equivalent to a yield to scheduler in other threading libraries
                time.sleep(0)

        except Exception as err:
            _LOGGER.exception(err)
92099
protected void handleTimeout(REQID rid) {
    if (contextMap.containsKey(rid)) {
      Object ctx = contextMap.get(rid);
      contextMap.remove(rid);
      responseMessageMap.remove(rid);
      onResponse(StatusCode.TIMEOUT_ERROR, ctx, null);
    } else {
      // Since we dont do cancel timer, this is because we already have
      // the response. So just disregard this timeout
      // TODO:- implement cancel timer to avoid this overhead
    }
  }
1249441
def _timeout_future(self, tag, matcher, future):
        '''
        
        '''
        if (tag, matcher) not in self.tag_map:
            return
        if not future.done():
            future.set_exception(TimeoutException())
            self.tag_map[(tag, matcher)].remove(future)
        if not self.tag_map[(tag, matcher)]:
            del self.tag_map[(tag, matcher)]
1212917
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		// Stop view stopwatch
		stopStopwatch();

		// Remove location
		threadLocation.remove();
	}
394625
private synchronized void cleanupThread ( long timeout ) throws TransportException {
        Thread t = this.thread;
        if ( t != null && Thread.currentThread() != t ) {
            this.thread = null;
            try {
                log.debug("Interrupting transport thread");
                t.interrupt();
                log.debug("Joining transport thread");
                t.join(timeout);
                log.debug("Joined transport thread");
            }
            catch ( InterruptedException e ) {
                throw new TransportException("Failed to join transport thread", e);
            }
        }
        else if ( t != null ) {
            this.thread = null;
        }
    }
458765
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) {
        if (unit == null)
            throw new NullPointerException();
        if (result == null)
            whenComplete(new Canceller(Delayer.delay(new Timeout(this),
                                                     timeout, unit)));
        return this;
    }
192757
def abort_request(self, request):
        """"""
        self.timedout = True
        try:
            request.cancel()
        except error.AlreadyCancelled:
            return
8012
function t(time, done) {
  if (arguments.length === 1) {
    done = time;
    time = 2000;
  }
  var error = new Error(`Callback took too long (max: ${time})`);
  var waiting = true;

  var timeout = setTimeout(function () {
    if (!waiting) return;
    waiting = false;
    done(error);
  }, time);

  function handler() {
    if (!waiting) return;
    clearTimeout(timeout);
    waiting = false;
    done.apply(this, arguments);
  }

  return handler;
}
903645
public static boolean discard(Source source, int timeout, TimeUnit timeUnit) {
    try {
      return skipAll(source, timeout, timeUnit);
    } catch (IOException e) {
      return false;
    }
  }
1038208
private void cancelIncompleteOperations(Iterable<CompletableOperation> operations, Throwable failException) {
        assert failException != null : "no exception to set";
        int cancelCount = 0;
        for (CompletableOperation o : operations) {
            if (!o.isDone()) {
                this.state.failOperation(o, failException);
                cancelCount++;
            }
        }

        log.warn("{}: Cancelling {} operations with exception: {}.", this.traceObjectId, cancelCount, failException.toString());
    }
119541
def cleanup(self, timeout):
        '''
        
        '''
        cutoff = time() - timeout
        self.collection.remove({_atime: {'$lt': cutoff}})
51178
public void cancel(TaskInProgress tip) {
    LOG.info("Canceling task "  + tip.getTask().getTaskID() + " of job " +
        tip.getTask().getJobID());
    // Cancel & remove the map completion finish thread for reduce tasks.
    if (!tip.getTask().isMapTask() && !tip.getTask().isTaskCleanupTask()) {
      if (!mapperWaitThreadMap.containsKey(tip)) {
        throw new RuntimeException("Mapper wait thread doesn't exist " +
            "for " + tip.getTask().getTaskID());
      }
      LOG.debug("Interrupting mapper wait thread for " +
          tip.getTask().getTaskID() + " job " +
          tip.getTask().getJobID());
      mapperWaitThreadMap.get(tip).interrupt();
      LOG.debug("Removing mapper wait thread for " +
          tip.getTask().getTaskID() + " job " + tip.getTask().getJobID());
      mapperWaitThreadMap.remove(tip);
    } else {
      LOG.debug(tip.getTask().getTaskID() + " is not a reduce task, so " +
          "not canceling mapper wait thread");
    }
    removeFromFinishingQueue(tip);
  }
798250
def _onMethodTimeout(self, serial, d):
        
        del self._pendingCalls[serial]
        d.errback(error.TimeOut('Method call timed out'))
473258
private void timeout() {
        lock.writeLock().lock();
        try {
            //if already stopped, do nothing, otherwise check times and run the timeout task
            if (!this.stopped) {
                long now = System.nanoTime();
                long remaining = this.targetEnd - now;
                this.timedout = remaining <= FTConstants.MIN_TIMEOUT_NANO;

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    debugTime("!Start  {0}", this.start);
                    debugTime("!Target {0}", this.targetEnd);
                    debugTime("!Now    {0}", now);
                    debugTime("!Remain {0}", remaining);
                }

                //if we really have timedout then run the timeout task
                if (this.timedout) {
                    debugRelativeTime("Timeout!");
                    this.timeoutTask.run();
                } else {
                    //this shouldn't be possible but if the timer popped too early, restart it
                    debugTime("Premature Timeout!", remaining);
                    start(this.timeoutTask, remaining);
                }
            }
        } finally {
            lock.writeLock().unlock();
        }
    }
1177056
public boolean deleteWithCustomTimeout(CompositeVoldemortRequest<K, V> deleteRequestObject) {
        List<Versioned<V>> versionedValues;

        validateTimeout(deleteRequestObject.getRoutingTimeoutInMs());
        boolean hasVersion = deleteRequestObject.getVersion() == null ? false : true;
        String keyHexString = "";
        if(!hasVersion) {
            long startTimeInMs = System.currentTimeMillis();
            if(logger.isDebugEnabled()) {
                ByteArray key = (ByteArray) deleteRequestObject.getKey();
                keyHexString = RestUtils.getKeyHexString(key);
                logger.debug("DELETE without version requested for key: " + keyHexString
                             + " , for store: " + this.storeName + " at time(in ms): "
                             + startTimeInMs + " . Nested GET and DELETE requests to follow ---");
            }
            // We use the full timeout for doing the Get. In this, we're being
            // optimistic that the subsequent delete might be faster all the
            // steps might finish within the allotted time
            deleteRequestObject.setResolveConflicts(true);
            versionedValues = getWithCustomTimeout(deleteRequestObject);
            Versioned<V> versioned = getItemOrThrow(deleteRequestObject.getKey(),
                                                    null,
                                                    versionedValues);

            if(versioned == null) {
                return false;
            }

            long timeLeft = deleteRequestObject.getRoutingTimeoutInMs()
                            - (System.currentTimeMillis() - startTimeInMs);

            // This should not happen unless there's a bug in the
            // getWithCustomTimeout
            if(timeLeft < 0) {
                throw new StoreTimeoutException("DELETE request timed out");
            }

            // Update the version and the new timeout
            deleteRequestObject.setVersion(versioned.getVersion());
            deleteRequestObject.setRoutingTimeoutInMs(timeLeft);

        }
        long deleteVersionStartTimeInNs = System.currentTimeMillis();
        if(logger.isDebugEnabled()) {
            ByteArray key = (ByteArray) deleteRequestObject.getKey();
            keyHexString = RestUtils.getKeyHexString(key);
            debugLogStart("DELETE",
                          deleteRequestObject.getRequestOriginTimeInMs(),
                          deleteVersionStartTimeInNs,
                          keyHexString);
        }
        boolean result = store.delete(deleteRequestObject);
        if(logger.isDebugEnabled()) {
            debugLogEnd("DELETE",
                        deleteRequestObject.getRequestOriginTimeInMs(),
                        deleteVersionStartTimeInNs,
                        System.currentTimeMillis(),
                        keyHexString,
                        0);
        }
        if(!hasVersion && logger.isDebugEnabled()) {
            logger.debug("DELETE without version response received for key: " + keyHexString
                         + ", for store: " + this.storeName + " at time(in ms): "
                         + System.currentTimeMillis());
        }
        return result;
    }
226415
@Override
	public void stopped() {

		// Stop timer
		ScheduledFuture<?> task = callTimeoutTimer.get();
		if (task != null) {
			task.cancel(false);
		}

		// Stop pending invocations
		Iterator<PendingPromise> pendingPromises = promises.values().iterator();
		while (pendingPromises.hasNext()) {
			PendingPromise pending = pendingPromises.next();
			pendingPromises.remove();
			try {
				pending.promise.complete(new RequestRejectedError(nodeID, pending.action));
			} catch (Throwable cause) {
				logger.warn("Unable to reject action \"" + pending.action + "\"!", cause);
			}
		}

		// Stop middlewares
		for (Middleware middleware : middlewares) {
			try {
				middleware.stopped();
			} catch (Throwable cause) {
				logger.warn("Unable to stop middleware \"" + middleware.name + "\"!", cause);
			}
		}

		// Stop registered services
		stopAllLocalServices();

		// Clear registries
		final long stamp = lock.writeLock();
		try {

			// Delete strategies (and registered actions)
			strategies.clear();

			// Delete all service names
			names.clear();

			// Delete middlewares
			middlewares.clear();

			// Delete cached node descriptor
			clearDescriptorCache();

		} finally {
			lock.unlockWrite(stamp);
		}
	}