Is called when a write timeout was detected
10743
protected void writeTimedOut(ChannelHandlerContext ctx) throws Exception {
        if (!closed) {
            ctx.fireExceptionCaught(WriteTimeoutException.INSTANCE);
            ctx.close();
            closed = true;
        }
    }
1202956
private void checkPotentiallyTimedOutConnection() {
    boolean stillCheckingTimeouts = true;
    while (stillCheckingTimeouts) {
      try {
        for (SelectionKey sk : selector.keys()) {
          MemcachedNode mn = (MemcachedNode) sk.attachment();
          if (mn.getContinuousTimeout() > timeoutExceptionThreshold) {
            getLogger().warn("%s exceeded continuous timeout threshold", sk);
            lostConnection(mn);
          }
        }
        stillCheckingTimeouts = false;
      } catch(ConcurrentModificationException e) {
        getLogger().warn("Retrying selector keys after "
          + "ConcurrentModificationException caught", e);
        continue;
      }
    }
  }
1116792
function ConnectionTimeoutError(timeout) {
    Error.call(this);
    Error.captureStackTrace(this, this.constructor);
    this.message = 'connection timed out';

    if (timeout) {
        this.message += '. timeout = ' + timeout + ' ms';
    }

    this.name = 'ConnectionTimeoutError';
}
1092748
private void timeoutHasExpired(final Timeout timeout, final TimeoutExpirationContext context) {
        try {
            addMessage(timeout, context.getOriginalHeaders());
        } catch (Exception ex) {
            LOG.error("Error handling timeout {}", timeout, ex);
        }
    }
1287471
private void checkTimeout() {
        if (timerMDC != null) {
            MDC.put("name", timerMDC);
        }
        if (docBuffer.isEmpty()) {
            return;
        }

        // How long has the NEWest item been waiting?
        long wait = ((new Date().getTime()) - bufferYoungest) / 1000;
        // If the buffer has been updated in the last 20s ignore it
        if (wait < 20) {
            return;
        }

        // Else, time to flush the buffer
        log.debug("=== Flushing old buffer: {}s", wait);
        submitBuffer(true);
    }
755000
def handle_write(self):
        """"""
        num_sent = self.send(self.write_buffer)
        if self.debug:
            if self.state is not STATE_NOT_STARTED or options.password is None:
                self.print_debug(b'<== ' + self.write_buffer[:num_sent])
        self.write_buffer = self.write_buffer[num_sent:]
1163660
function Timeout(clusterUtils, name, func, delay) {
    this._clusterUtils = clusterUtils;
    this._func = func;

    this.lockKey = util.format('ClusterUtils:setTimeout:Lock:%s', name);
    this.timeoutId = setTimeout(_runIfLocked.bind(this), delay);
}
312505
def _net_write(sock, data, expiration):
    
    current = 0
    l = len(data)
    while current < l:
        _wait_for_writable(sock, expiration)
        current += sock.send(data[current:])
1183775
public void waitUntilAllWritten(int timeout) throws ExternalFrameConfirmationException {
        final AutoBuffer confirmAb = new AutoBuffer(channel);
        try {
            byte flag = ExternalFrameConfirmationCheck.getConfirmation(confirmAb, timeout);
            assert (flag == ExternalFrameHandler.CONFIRM_WRITING_DONE);
        } catch (TimeoutException ex) {
            throw new ExternalFrameConfirmationException("Timeout for confirmation exceeded!");
        } catch (InterruptedException e) {
            throw new ExternalFrameConfirmationException("Confirmation thread interrupted!");
        } catch (ExecutionException e) {
            throw new ExternalFrameConfirmationException("Confirmation failed!");
        }
    }
876792
public boolean isValidTimeout(AllocationID allocationId, UUID ticket) {
		checkInit();

		return timerService.isValid(allocationId, ticket);
	}
438672
function internalStop(test) {
  	test.semaphore += 1;
  	config.blocking = true;

  	// Set a recovery timeout, if so configured.
  	if (defined.setTimeout) {
  		var timeoutDuration = void 0;

  		if (typeof test.timeout === "number") {
  			timeoutDuration = test.timeout;
  		} else if (typeof config.testTimeout === "number") {
  			timeoutDuration = config.testTimeout;
  		}

  		if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  			clearTimeout(config.timeout);
  			config.timeout = setTimeout(function () {
  				pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
  				internalRecover(test);
  			}, timeoutDuration);
  		}
  	}

  	var released = false;
  	return function resume() {
  		if (released) {
  			return;
  		}

  		released = true;
  		test.semaphore -= 1;
  		internalStart(test);
  	};
  }
263946
@Override
    public long write(long numBytes, int time) throws IOException {
        int timeout = time;
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "write(" + numBytes + "," + timeout + ")");
        }
        getTCPConnLink().incrementNumWrites();
        if (getConfig().getDumpStatsInterval() > 0) {
            getTCPConnLink().getTCPChannel().totalSyncWrites.incrementAndGet();
        }
        // always check external call parms
        checkForErrors(numBytes, false, timeout);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Socket socket = getTCPConnLink().getSocketIOChannel().getSocket();
            Tr.event(tc, "write (sync) requested for local: " + socket.getLocalSocketAddress() + " remote: " + socket.getRemoteSocketAddress());
        }

        long numUserBytesWritten = 0L; // no. of user bytes written

        if (isAborted()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Previously aborted, unable to perform write");
            }
            throw new IOException("Connection aborted by program");
        }

        if (timeout == IMMED_TIMEOUT) {
            immediateTimeout();
        } else if (timeout == ABORT_TIMEOUT) {
            abort();
            immediateTimeout();
        } else {
            // if using channel timeout, reset to that value
            if (timeout == TCPRequestContext.USE_CHANNEL_TIMEOUT) {
                timeout = getConfig().getInactivityTimeout();
            }
            // check if this is a FileChannel write request
            if (isFileChannelWriteToBeDone()) {
                numUserBytesWritten = fileChannelWrite(numBytes, timeout);
            } else {
                numUserBytesWritten = processSyncWriteRequest(numBytes, timeout);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "write(sync): " + numUserBytesWritten);
        }
        return (numUserBytesWritten);
    }
393594
def _timeout(self, timeout, handler, *args, **kw):
        
        t = spawn_thread(target=handler, args=args, kw=kw)
        t.daemon = True
        t.start()
        t.join(timeout)

        if not t.is_alive():
            if t.exc_info:
                return t.exc_info
            return t.result
        else:
            try:
                msg = '[%s] Execution was forcefully terminated'
                raise RuntimeError(msg % t.name)
            except:
                return sys.exc_info()
612318
def timeout_per_mb(seconds_per_mb, size_bytes):
    
    result = seconds_per_mb * (size_bytes / 1e6)
    if result < DEFAULT_TIMEOUT:
        return DEFAULT_TIMEOUT
    return result
1302797
@Override
    public synchronized void timeoutTransaction(boolean initial) {
        final boolean traceOn = TraceComponent.isAnyTracingEnabled();

        if (traceOn && tc.isEntryEnabled())
            Tr.entry(tc, "timeoutTransaction", initial);

        if (traceOn && tc.isEventEnabled())
            Tr.event(tc, "(SPI) Transaction TIMEOUT occurred for TX: " + getLocalTID());

        _timedOut = true; // mark

        if (initial) // initial timeout
        {
            _rollbackOnly = true;

            abortTransactionParticipants();

            // inactivity timeout may have happened ... check status
            if (_status.getState() == TransactionState.STATE_ACTIVE) {
                // If there is no txn timeout, or we are into completion phase the timeout setting may be zero
                if (_timeout == 0)
                    _timeout = 10;
                EmbeddableTimeoutManager.setTimeout(this, EmbeddableTimeoutManager.REPEAT_TIMEOUT, _timeout);

                // d369039 only rollback if still in ACTIVE state
                if (_activeAssociations <= 0) {
                    rollbackResources();
                }
            }
        } else if (_activeAssociations <= 0) // off server ... do the rollback
        {
            final EmbeddableTranManagerSet tranManager = (EmbeddableTranManagerSet) TransactionManagerFactory.getTransactionManager();

            boolean resumed = false;
            try {
                tranManager.resume(this);
                resumed = true;
            } catch (Throwable t) {
                FFDCFilter.processException(t, "com.ibm.ws.tx.jta.TransactionImpl.timeoutTransaction", "1311", this);
                if (traceOn && tc.isDebugEnabled())
                    Tr.debug(tc, "timeoutTransaction resume threw exception", t);
                // swallow this exception
            }

            if (resumed) {
                boolean rolledback = false;
                try {
                    tranManager.rollback();
                    rolledback = true;
                } catch (Throwable t) {
                    FFDCFilter.processException(t, "com.ibm.ws.tx.jta.TransactionImpl.timeoutTransaction", "1326", this);
                    if (traceOn && tc.isDebugEnabled())
                        Tr.debug(tc, "timeoutTransaction rollback threw exception", t);
                    // swallow this exception
                } finally {
                    if (!rolledback) {
                        tranManager.suspend();
                    }
                }
            }
        } else // on server ... just re-schedule timeout
        {
            _rollbackOnly = true; // for the case of server quiesce?
            // inactivity timeout may have happened ... check status
            if (_status.getState() == TransactionState.STATE_ACTIVE) {
                // If there is no txn timeout, or we are into completion phase the timeout setting may be zero
                if (_timeout == 0)
                    _timeout = 10;
                EmbeddableTimeoutManager.setTimeout(this, EmbeddableTimeoutManager.REPEAT_TIMEOUT, _timeout);
            }
        }

        if (traceOn && tc.isEntryEnabled())
            Tr.exit(tc, "timeoutTransaction");
    }
605280
boolean detectAndHandleBackupTimeout(long timeoutMillis) {
        // if the backups have completed, we are done; this also filters out all non backup-aware operations
        // since the backupsAcksExpected will always be equal to the backupsAcksReceived
        boolean backupsCompleted = backupsAcksExpected == backupsAcksReceived;
        long responseReceivedMillis = pendingResponseReceivedMillis;

        // if this has not yet expired (so has not been in the system for a too long period) we ignore it
        long expirationTime = responseReceivedMillis + timeoutMillis;
        boolean timeout = expirationTime > 0 && expirationTime < Clock.currentTimeMillis();

        // if no response has yet been received, we we are done; we are only going to re-invoke an operation
        // if the response of the primary has been received, but the backups have not replied
        boolean responseReceived = pendingResponse != VOID;

        if (backupsCompleted || !responseReceived || !timeout) {
            return false;
        }

        if (shouldFailOnIndeterminateOperationState()) {
            complete(new IndeterminateOperationStateException(this + " failed because backup acks missed."));
            return true;
        }

        boolean targetDead = context.clusterService.getMember(targetAddress) == null;
        if (targetDead) {
            // the target doesn't exist, so we are going to re-invoke this invocation;
            // the reason for the re-invocation is that otherwise it's possible to lose data,
            // e.g. when a map.put() was done and the primary node has returned the response,
            // but has not yet completed the backups and then the primary node fails;
            // the consequence would be that the backups are never be made and the effects of the map.put() will never be visible,
            // even though the future returned a value;
            // so if we would complete the future, a response is sent even though its changes never made it into the system
            resetAndReInvoke();
            return false;
        }

        // the backups have not yet completed, but we are going to release the future anyway if a pendingResponse has been set
        complete(pendingResponse);
        return true;
    }
699900
public void processTimeout(final TimeoutEvent timeoutEvent) {
		Transaction eventTransaction = null;
		if(timeoutEvent.isServerTransaction()) {
			eventTransaction = timeoutEvent.getServerTransaction();
		} else {
			eventTransaction = timeoutEvent.getClientTransaction();
		}
		final Transaction transaction = eventTransaction;
		if(logger.isDebugEnabled()) {
			logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
		}

		final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
		if(tad != null && tad.getSipServletMessage() != null) {
			// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
			final SipServletMessageImpl sipServletMessage = tad.getSipServletMessage();
			final MobicentsSipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey();
			final MobicentsSipSession sipSession = sipServletMessage.getSipSession();
			getAsynchronousExecutor().execute(new Runnable() {
				public void run() {
					try {
						if(logger.isDebugEnabled()) {
							logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
						}
						boolean appNotifiedOfPrackNotReceived = false;
						// session can be null if a message was sent outside of the container by the container itself during Initial request dispatching
						// but the external host doesn't send any response so we call out to the application only if the session is not null
						if(logger.isDebugEnabled()) {
                            logger.debug("time out happened on sipSession " + sipSession);
                        }
						if(sipSession != null) {
							SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
							//the context can be null if the server is being shutdown
							if(sipContext != null) {
								MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
								try {
									sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);
									MobicentsB2BUAHelper b2buaHelperImpl = sipSession.getB2buaHelper();

									if(b2buaHelperImpl != null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
										b2buaHelperImpl.unlinkRequestInternal((SipServletRequestImpl)tad.getSipServletMessage(), false);
									}
									// naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions
									if(logger.isDebugEnabled()) {
			                            logger.debug("time out happened on server tx ? " + timeoutEvent.isServerTransaction() + " and message " + sipServletMessage);
			                        }
									if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) {
										try {
											ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch();
											if(proxyBranchImpl != null) {
												ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy();
												if(proxy.getFinalBranchForSubsequentRequests() != null) {
													tad.cleanUp();
													transaction.setApplicationData(null);
													return;
												}
											}
											SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage;
											if(sipServletRequestImpl.visitNextHop()) {
												return;
											}
											sipServletMessage.setTransaction(transaction);
											SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false, true);
											// Fix for Issue 1734
											sipServletRequestImpl.setResponse(response);
											MessageDispatcher.callServlet(response);
											if(tad.getProxyBranch() != null) {
												tad.getProxyBranch().setResponse(response);
												tad.getProxyBranch().onResponse(response, response.getStatus());
											}
											sipSession.updateStateOnResponse(response, true);
										} catch (Throwable t) {
											logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t);
										}
									}
									// Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350
									// Should check only Server Tx for ack or prack not received http://code.google.com/p/mobicents/issues/detail?id=2525
									if(Request.INVITE.equals(sipServletMessage.getMethod()) && timeoutEvent.isServerTransaction()) {
										checkForAckNotReceived(sipServletMessage);
										appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage);
									}
								} finally {
									sipSession.removeOngoingTransaction(transaction);
									sipSession.setRequestsPending(0);
									sipContext.exitSipApp(sipApplicationSession, sipSession);
								}
								// don't invalidate here because if the application sends a final response on the noPrack received
								// the ACK to this final response won't be able to get routed since the sip session would have been invalidated
								if(!appNotifiedOfPrackNotReceived) {
									tryToInvalidateSession(sipSessionKey, false);
								}
							}
						}
						// don't clean up for the same reason we don't invalidate the sip session right above
						tad.cleanUp();
						transaction.setApplicationData(null);
					} catch (Exception e) {
						logger.error("Problem handling timeout", e);
					}
				}
			});
		}
	}