Run.

@param runnableWork the runnable work
@param timeoutInSec the timeout in sec
761205
public static void run(final Runnable runnableWork,
            final long timeoutInSec) {
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        afterTimeout(timeoutInSec, threadPool, threadPool.submit(runnableWork));
    }
148699
synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) {
        if (this.scheduledFuture != null) {
            throw new IllegalArgumentException("Reporter already started");
        }

        this.scheduledFuture = executor.scheduleAtFixedRate(runnable, initialDelay, period, unit);
    }
526769
public static LauncherStatus runHelloReef(final Configuration runtimeConf, final int timeOut)
      throws BindException, InjectionException {
    final Configuration driverConf =
        Configurations.merge(HelloREEFHttp.getDriverConfiguration(), getHTTPConfiguration());
    return DriverLauncher.getLauncher(runtimeConf).run(driverConf, timeOut);
  }
536913
@Override
	public void run() {

		final Map<String, WatchEventItem> eventQueue = new LinkedHashMap<>();

		while (running) {

			if (!Services.getInstance().isInitialized()) {

				try { Thread.sleep(100); } catch (InterruptedException i) {}

				// loop until we are stopped
				continue;
			}

			synchronized (watchedRoots) {

				for (final FolderInfo info : watchedRoots.values()) {

					if (info.shouldScan()) {

						// update last scanned timestamp
						info.setLastScanned(System.currentTimeMillis());

						// start a new scan thread
						new Thread(new ScanWorker(false, Paths.get(info.getRoot()), info.getRoot(), true)).start();
					}
				}
			}

			try {

				final WatchKey key = watchService.poll(100, TimeUnit.MILLISECONDS);
				if (key != null && Services.getInstance().isInitialized()) {

					final Path root;

					// synchronize access to map but keep critical section short
					synchronized (watchKeyMap) {
						root = watchKeyMap.get(key);
					}

					if (root != null) {

							for (final WatchEvent event : key.pollEvents()) {

								final Kind kind = event.kind();

								if (OVERFLOW.equals(kind)) {
									continue;
								}

								addToQueue(eventQueue, new WatchEventItem(root, (Path)key.watchable(), event));
							}

							key.reset();

					} else {

						key.cancel();
					}
				}

			} catch (InterruptedException ex) {
				ex.printStackTrace();
			}

			final SecurityContext securityContext = SecurityContext.getSuperUserInstance();

			try (final Tx tx = StructrApp.getInstance(securityContext).tx(true, true, false)) {

				// handle all watch events that are older than 2 seconds
				for (final Iterator<WatchEventItem> it = eventQueue.values().iterator(); it.hasNext();) {

					final WatchEventItem item = it.next();
					if (item.olderThan(2000)) {

						handleWatchEvent(true, item);

						it.remove();
					}
				}

				tx.success();

			} catch (Throwable t) {

				t.printStackTrace();
			}

		}

		logger.info("DirectoryWatchService stopped");
	}
496073
public static void runIgnoringConstraintViolation(Runnable task)
    {
        try {
            task.run();
        }
        catch (RuntimeException e) {
            if (!sqlCodeStartsWith(e, "23")) {
                throw e;
            }
        }
    }
1034840
public void processTimedoutEntries(List timedout)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "processTimedoutEntries", new Object[] {this,timedout});

    boolean sendMsg = false;
    synchronized (this)
    {
      if (active && completedTicksInitialized && !timedout.isEmpty())
      {
        sendMsg = true;
      }
    }
    if (sendMsg)
      parent.sendDecisionExpected(remoteMEUuid, gatheringTargetDestUuid, streamId, timedout);

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "processTimedoutEntries");
  }
366649
public void probe(long timeoutInMs) {
    long start = System.nanoTime();

    try {
      while (!condition.call() && (elapsedMs(start) < timeoutInMs)) {
        Thread.yield();
      }

      if (!condition.call()) {
        throw new IllegalStateException("probe condition not true after " + timeoutInMs);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
959951
public static void executorShutDown(ExecutorService executorService, long timeOutSec) {
        try {
            executorService.shutdown();
            executorService.awaitTermination(timeOutSec, TimeUnit.SECONDS);
        } catch(Exception e) {
            logger.warn("Error while stoping executor service.", e);
        }
    }
960104
public void run(Runnable runnable, Executor executor)
    {
        if (this.goForward())
        {
            for (int i = this.from; i <= this.to; i += this.step)
            {
                executor.execute(runnable);
            }
        }
        else
        {
            for (int i = this.from; i >= this.to; i += this.step)
            {
                executor.execute(runnable);
            }
        }
    }
1107271
@Override
  public void execute(Runnable runnable) {
    if (runnable == null) {
      throw new NullPointerException("runnable parameter is null");
    }

    if (!mWorkQueue.offer(runnable)) {
      throw new RejectedExecutionException(
          mName + " queue is full, size=" + mWorkQueue.size());
    }

    final int queueSize = mWorkQueue.size();
    final int maxSize = mMaxQueueSize.get();
    if ((queueSize > maxSize) && mMaxQueueSize.compareAndSet(maxSize, queueSize)) {
      FLog.v(TAG, "%s: max pending work in queue = %d", mName, queueSize);
    } // else, there was a race and another thread updated and logged the max queue size

    startWorkerIfNeeded();
  }
585851
@Override
	public void run() {
		long currentTime = timeProvider.currentTime();
		for(Job job : scheduler.jobStatus()) {
			cleanUpLongJobIfItHasFinishedExecuting(currentTime, job);
			detectLongRunningJob(currentTime, job);
		}
	}
58399
protected void joinSchedulerDriver(long timeout, TimeUnit unit) {
    // ExecutorService used to monitor whether close() completes in time
    ExecutorService service = Executors.newFixedThreadPool(1);
    final CountDownLatch closeLatch = new CountDownLatch(1);
    Runnable driverJoin = new Runnable() {
      @Override
      public void run() {
        driver.join();
        closeLatch.countDown();
      }
    };
    service.submit(driverJoin);

    LOG.info("Waiting for Mesos Driver got stopped");
    try {
      if (!closeLatch.await(timeout, unit)) {
        LOG.severe("Mesos Driver failed to stop in time.");
      } else {
        LOG.info("Mesos Driver stopped.");
      }
    } catch (InterruptedException e) {
      LOG.log(Level.SEVERE, "Close latch thread is interrupted: ", e);
    }

    // Shutdown the ExecutorService
    service.shutdownNow();
  }
923960
public synchronized void setTimeout(int timeout) {
        try {
            this.timeout = timeout;
            if (socket != null) {
                socket.setSoTimeout(timeout);
            }
        }
        catch (IOException ex) {
            logger.warn("Could not set timeout to value " + timeout, ex);
        }
    }
611912
public boolean start(Runnable task, long timeout)
  {
    long expire;

    if (timeout < 0 || timeout > MAX_EXPIRE)
      expire = MAX_EXPIRE;
    else
      expire = CurrentTime.getCurrentTimeActual() + timeout;

    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    boolean isPriority = false;
    boolean isQueue = false;
    boolean isWake = true;

    return scheduleImpl(task, loader, expire, isPriority, isQueue, isWake);
  }
903867
@Override
	public void setTransactionTimeout(int seconds) throws TransactionManagementException {
		logger.entering(CLASSNAME, "setTransactionTimeout", seconds);
		try {
			userTran.setTransactionTimeout(seconds);
		} catch (SystemException e) {
			throw new TransactionManagementException(e);
		}
		logger.exiting(CLASSNAME, "setTransactionTimeout");
	}
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);
					}
				}
			});
		}
	}
35622
protected final void runOnUiThread(@NonNull Runnable runnable) {
        checkNotNull(runnable, "runnable");
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
        } else {
            mPoster.post(runnable);
        }
    }