This method is used to extend the already locked resource in the prepare phase of the transactions.
It also marks the resource true to block reads.

@param caller
@param threadId
@param leaseTime
@return
175074
boolean extendLeaseTime(String caller, long threadId, long leaseTime) {
        if (!isLockedBy(caller, threadId)) {
            return false;
        }
        this.blockReads = true;
        if (expirationTime < Long.MAX_VALUE) {
            setExpirationTime(expirationTime - Clock.currentTimeMillis() + leaseTime);
        }
        return true;
    }
945219
public @Nonnull SetType derive(@Nonnull Collection<ThreadType> threads) {
        return runtime.getThreadSet(threads);
    }
1018000
public final void acquire(long timeout) throws RuntimeException {
		synchronized (this.LOCK) {
			long start = System.currentTimeMillis();

			while (this.owner != null) {
				if (this.owner.get() == Thread.currentThread()) {
					this.acquire++;

					return;
				}

				try {
					if (timeout == -1) {
						this.LOCK.wait();
					} else {
						this.LOCK.wait(timeout);
					}
				} catch (InterruptedException e) {
					//
				}

				long end = System.currentTimeMillis();

				if ((this.owner != null) && (timeout != -1)
						&& ((end - start) >= timeout)) {
					throw new RuntimeException("TimeoutException");
				}
			}

			this.owner = new WeakReference(Thread.currentThread());
			this.acquire++;
		}
	}
700146
@Deprecated
    public ClientConfig setThreadIdleTime(long threadIdleTime, TimeUnit unit) {
        this.threadIdleMs = unit.toMillis(threadIdleTime);
        return this;
    }
1120981
private void synchronizePropertiesWithCRI() throws ResourceException {

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        int previousTransactionIsolation = -1; // only used for debugging
        int previousHoldability = -1; //  - only used for debugging

        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(this, tc, "synchronizePropertiesWithCRI");

        try {
            isolationChanged = false;
            holdabilityChanged = false;

            if (kerberosConnection) {
                if (!AdapterUtil.matchGSSName(mc_gssName, cri.gssName)) {
                    if (isTraceOn && tc.isDebugEnabled()) 
                    {
                        Tr.debug(this, tc, "synching kerberos gssCredential on this mc and then clearing ps cache");
                    }

                    //  move the clearing of statement to before we issue the reuse.
                    // this will cover for cases where the reuse results in bad stuff. DB2 on Z seem to leak when this happens.
                    // reuse is supported with clean model only

                    // the cache gets created after the synchronizePropertiesWithCRI on newly created mc.
                    // thus, we should only call it if its not null here.  We don't want to have the check
                    // happen at the clearSTatementCache() since it puts a tr that cache is disabled (which si not the case)
                    if (statementCache != null) {
                        clearStatementCache();
                    }

                    // the reuse call won't go down to the DB til the next execution of the.  DB optimizaiton.
                    // if we were in a tran, a connection will have to match as we do compare subject and CRI
                    // the fact that the gssNames don't match, means we are not in a tra.
                    mcf.helper.reuseKerbrosConnection(sqlConn, cri.gssCredential, null);

                    //now save the cri props in the mc
                    mc_gssCredential = cri.gssCredential;
                    mc_gssName = cri.gssName;

                    // now that we issued the reuse, we need to purge the PS cache for this mc as
                    // reuse is supported with clean model only

                    handleCleanReuse();
                }
            }

            // Retrieve the default values for all Connection properties. 
            // Save the default values for when null is specified in the CRI. 
            previousTransactionIsolation = getTransactionIsolation();
            previousHoldability = currentHoldability;

            if (currentTransactionIsolation != cri.ivIsoLevel) {
                setTransactionIsolation(cri.ivIsoLevel);
            }

            if (cri.ivCatalog != null && !cri.ivCatalog.equals(defaultCatalog)) {
                setCatalog(cri.ivCatalog);
            }


            if (cri.ivReadOnly != null && defaultReadOnly != cri.ivReadOnly.booleanValue() && mcf.supportsIsReadOnly) {
                helper.setReadOnly(this, cri.ivReadOnly.booleanValue(), false); 
            }

            if (!AdapterUtil.match(cri.ivShardingKey, currentShardingKey)
             || !AdapterUtil.match(cri.ivSuperShardingKey, currentSuperShardingKey)) {
                setShardingKeys(cri.ivShardingKey, cri.ivSuperShardingKey);
            }

            if (cri.ivTypeMap != null && defaultTypeMap != cri.ivTypeMap && mcf.supportsGetTypeMap) {
                setTypeMap(cri.ivTypeMap);
            }
            
            if (mcf.supportsGetNetworkTimeout && cri.ivNetworkTimeout != currentNetworkTimeout) {
                final ExecutorService libertyThreadPool = mcf.connectorSvc.getLibertyThreadPool();
                // setNetworkTimeout is the only JDBC Connection property that may perform access checks
                if (System.getSecurityManager() == null) {
                    setNetworkTimeout(libertyThreadPool, cri.ivNetworkTimeout);
                } else {
                    try {
                        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
                            @Override
                            public Void run() throws Exception {
                                setNetworkTimeout(libertyThreadPool, cri.ivNetworkTimeout);
                                return null;
                            }
                        });
                    } catch (PrivilegedActionException e) {
                        if (e.getException() instanceof SQLException)
                            throw (SQLException) e.getException();
                        throw (RuntimeException) e.getException();
                    }
                }
            }

            if(mcf.supportsGetSchema && (cri.ivSchema != null || defaultSchema != null)){
                String targetSchema = cri.ivSchema == null ? defaultSchema : cri.ivSchema;
                if(!AdapterUtil.match(currentSchema, targetSchema))
                    setSchema(targetSchema);
            }

            //  - synchronize the holdability value to either cri value or default value
            // if the default value is not 0, which means the JDBC driver supports holdability.
            if (defaultHoldability != 0) {
                int targetHoldability = cri.ivHoldability == 0 ?
                                defaultHoldability : cri.ivHoldability;
                if (currentHoldability != targetHoldability) {
                    setHoldability(targetHoldability);
                }
            }

        } catch (SQLException sqlX) {
            FFDCFilter.processException(sqlX, getClass().getName() + ".synchronizePropertiesWithCRI", "850", this);
            ResourceException x = AdapterUtil.translateSQLException(sqlX, this, true, getClass()); 
            if (isTraceOn && tc.isEntryEnabled())
                Tr.exit(this, tc, "synchronizePropertiesWithCRI", sqlX);
            throw x;
        }

        if (isTraceOn && tc.isDebugEnabled()) 
        {
            Tr.debug(this, tc, "previous/current value:",
                                   "AutoCommit:    " + currentAutoCommit + "/" + currentAutoCommit,
                                   "Isolation:     " + AdapterUtil.getIsolationLevelString(previousTransactionIsolation) +
                                                   "/" + AdapterUtil.getIsolationLevelString(currentTransactionIsolation),
                                   "Catalog:       " + defaultCatalog + "/" + (cri.ivCatalog == null ? defaultCatalog : cri.ivCatalog),
                                   "Schema:        " + defaultSchema + "/" + (cri.ivSchema == null ? defaultSchema : cri.ivSchema),
                                   "ShardingKey:   " + initialShardingKey + "/" + cri.ivShardingKey,
                                   "SuperShardingK:" + initialSuperShardingKey + "/" + cri.ivSuperShardingKey,
                                   "NetworkTimeout:" + defaultNetworkTimeout + "/" + (cri.ivNetworkTimeout == 0 ? defaultNetworkTimeout : cri.ivNetworkTimeout),
                                   "IsReadOnly:    " + defaultReadOnly + "/" + (cri.ivReadOnly == null ? defaultReadOnly : cri.ivReadOnly), 
                                   "TypeMap:       " + defaultTypeMap + "/" + (cri.ivTypeMap == null ? defaultTypeMap : cri.ivTypeMap),
                                   "Holdability:   " + AdapterUtil.getCursorHoldabilityString(previousHoldability) +
                                                   "/" + AdapterUtil.getCursorHoldabilityString(currentHoldability));
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(this, tc, "synchronizePropertiesWithCRI");

    }
711847
public void acquireLock (final NodeObject.Lock lock, final ResultListener<String> listener)
    {
        // wait until any pending resolution is complete
        queryLock(lock, new ChainedResultListener<String, String>(listener) {
            public void requestCompleted (String result) {
                if (result == null) {
                    if (_suboids.isEmpty()) {
                        lockAcquired(lock, 0L, listener);
                    } else {
                        _locks.put(lock, new LockHandler(lock, true, listener));
                    }
                } else {
                    listener.requestCompleted(result);
                }
            }
        });
    }
599372
@SuppressWarnings("unchecked")
    public void runDeadlockFuture(Runnable deadlockGuardTask) {
        if (deadlockFuture == null) {
            ThreadPoolTaskScheduler deadlockGuard = conn.getDeadlockGuardScheduler();
            if (deadlockGuard != null) {
                try {
                    deadlockFuture = (ScheduledFuture<Runnable>) deadlockGuard.schedule(deadlockGuardTask, new Date(packet.getExpirationTime()));
                } catch (TaskRejectedException e) {
                    log.warn("DeadlockGuard task is rejected for {}", sessionId, e);
                }
            } else {
                log.debug("Deadlock guard is null for {}", sessionId);
            }
        } else {
            log.warn("Deadlock future is already create for {}", sessionId);
        }
    }
736282
@Override
  public Serializable schedule(String sessionId, String timerName, long milliseconds) throws IllegalArgumentException {
    String id = sessionId + "/" + timerName;
    logger.debug("Scheduling timer with id [{}]", id);
    TimerTaskHandle ir = borrowTimerTaskHandle();
    ir.id = id;
    ir.sessionId = sessionId;
    ir.timerName = timerName;
    ir.future = this.executor.schedule(ir, milliseconds, TimeUnit.MILLISECONDS);
    return ir;
  }
677543
synchronized Lease reassignLease(Lease lease, String src, String newHolder) {
     assert newHolder != null : "new lease holder is null";
     LeaseOpenTime leaseOpenTime = null;
     if (lease != null) {
       leaseOpenTime = removeLease(lease, src);
     }
     return addLease(newHolder, src,
                     leaseOpenTime != null ?
                     leaseOpenTime.openTime :
                     System.currentTimeMillis());
   }
558752
@Override
    public Object preInvoke(EJSDeployedSupport s, ContainerTx tx) throws RemoteException {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "preInvoke : " + this);

        // If this is container managed concurrency control, then use
        // then get the lock specified by the lock type found in the
        // EJB method info object.
        s.ivLockAcquired = false; // d571981
        if (ivContainerManagedConcurrency) {
            // Get the lock type to use for the method being invoked.
            // and AccessTimeout value to use.
            EJBMethodInfoImpl mInfo = s.methodInfo;
            LockType lockType = mInfo.ivLockType;

            // Ensure we are not trying to upgrade from a READ to a WRITE lock. We
            // must throw an exception if trying to upgrade from READ to WRITE.
            if (lockType == LockType.WRITE && ivLock.isWriteLockedByCurrentThread() == false) {
                // Requesting write lock and write lock is not currently held by the
                // calling thread. So check whether calling thread holds any read locks.
                if (ivLock.getReadHoldCount() > 0) {
                    throw new IllegalLoopbackException("A loopback method call is not allowed to upgrade from a READ to a WRITE lock.");
                }
            }

            if (isTraceOn && tc.isDebugEnabled())
                Tr.debug(tc, "preInvoke attempting to acquire a " + mInfo.ivLockType.name() + " lock. " + ivLock.toString());

            // PMI startLockTime for read and write locks  F743-9002
            long lockStartTime = 0;
            int lockStatType = 0;

            try {
                long timeout = mInfo.ivAccessTimeout;

                // For a persistent timeout callback that will wait a significant amount of
                // time for the lock, perform a quick lock attempt in an effort to detect a
                // deadlock that can occur between the singleton lock and the timer database
                // if there is a concurrent thread calling getTimers().             RTC126471
                if (s.isPersistentTimeoutGlobalTx &&
                    PersistentTimerSingletonDeadlockTimeout >= 0 &&
                    (timeout == -1 || timeout > PersistentTimerSingletonDeadlockTimeout)) {
                    if (lockType == LockType.READ) {
                        if (pmiBean != null) {
                            lockStatType = EJBPMICollaborator.READ_LOCK_TIME;
                            lockStartTime = pmiBean.initialTime(lockStatType);
                        }
                        s.ivLockAcquired = ivReadLock.tryLock(PersistentTimerSingletonDeadlockTimeout, TimeUnit.MILLISECONDS);
                    } else {
                        if (pmiBean != null) {
                            lockStatType = EJBPMICollaborator.WRITE_LOCK_TIME;
                            lockStartTime = pmiBean.initialTime(lockStatType);
                        }
                        s.ivLockAcquired = ivWriteLock.tryLock(PersistentTimerSingletonDeadlockTimeout, TimeUnit.MILLISECONDS);
                    }

                    if (s.ivLockAcquired) {
                        if (isTraceOn && tc.isDebugEnabled())
                            Tr.debug(tc, "preInvoke acquired a " + mInfo.ivLockType.name() + " lock. " + ivLock.toString());
                    } else {
                        // If the lock was not obtained and another thread is in getTimer,
                        // then a deadlock is very likely, so abort the timeout callback
                        // which will free up the database row lock.
                        if (ivInGetTimers.get() > 0) {
                            if (pmiBean != null) {
                                pmiBean.countCancelledLocks();
                            }
                            throw new ConcurrentAccessTimeoutException("preInvoke timed out in attempt to acquire a "
                                                                       + mInfo.ivLockType.name() + " lock for method signature = " + mInfo.getMethodSignature()
                                                                       + ".  Dead lock detected with timer database.");
                        }

                        // Otherwise, subtract the time waited, and proceed normally
                        if (timeout != -1) {
                            timeout = Math.max(0, timeout - PersistentTimerSingletonDeadlockTimeout);
                        }
                    }
                }

                // If the lock is not acquired, then either this is not for a persistent
                // timeout callback, or there is not a concurrent thread in getTimers(),
                // so just attempt to obtain a lock using the configured access timeout.
                if (!s.ivLockAcquired) {
                    if (timeout == -1) // -1 means wait forever     F743-21028.5
                    {
                        if (lockType == LockType.READ) {
                            if (pmiBean != null && lockStartTime == 0) // F743-9002
                            {
                                lockStatType = EJBPMICollaborator.READ_LOCK_TIME;
                                lockStartTime = pmiBean.initialTime(lockStatType);
                            }
                            ivReadLock.lock(); // d571981
                        } else {
                            if (pmiBean != null && lockStartTime == 0)// F743-9002
                            {
                                lockStatType = EJBPMICollaborator.WRITE_LOCK_TIME;
                                lockStartTime = pmiBean.initialTime(lockStatType);
                            }
                            ivWriteLock.lock(); // d571981
                        }

                        s.ivLockAcquired = true;
                        if (isTraceOn && tc.isDebugEnabled())
                            Tr.debug(tc, "preInvoke acquired a " + mInfo.ivLockType.name() + " lock. " + ivLock.toString());
                    } else {
                        if (lockType == LockType.READ) {
                            if (pmiBean != null && lockStartTime == 0) // F743-9002
                            {
                                lockStatType = EJBPMICollaborator.READ_LOCK_TIME;
                                lockStartTime = pmiBean.initialTime(lockStatType);
                            }
                            s.ivLockAcquired = ivReadLock.tryLock(timeout, TimeUnit.MILLISECONDS); // d571981
                        } else {
                            if (pmiBean != null && lockStartTime == 0) // F743-9002
                            {
                                lockStatType = EJBPMICollaborator.WRITE_LOCK_TIME;
                                lockStartTime = pmiBean.initialTime(lockStatType);
                            }
                            s.ivLockAcquired = ivWriteLock.tryLock(timeout, TimeUnit.MILLISECONDS); // d571981
                        }

                        if (s.ivLockAcquired) {
                            if (isTraceOn && tc.isDebugEnabled())
                                Tr.debug(tc, "preInvoke acquired a " + mInfo.ivLockType.name() + " lock. " + ivLock.toString());
                        } else {
                            if (pmiBean != null) // F743-9002
                            {
                                pmiBean.countCancelledLocks();
                            }

                            throw new ConcurrentAccessTimeoutException("preInvoke timed out in attempt to acquire a "
                                                                       + mInfo.ivLockType.name() + " lock for method signature = " + mInfo.getMethodSignature()
                                                                       + ".  Access timeout value = " + timeout + " milli-seconds");
                        }
                    }
                }
            } catch (InterruptedException e) {
                if (isTraceOn && tc.isDebugEnabled())
                    Tr.debug(tc, "InterruptedException prevented lock from being acquired.");

                if (pmiBean != null) // F743-9002
                {
                    pmiBean.countCancelledLocks();
                }

                throw ExceptionUtil.EJBException("InterruptedException prevented lock from being acquired.", e);
            } finally {
                // F743-9002
                // Calculate the time to obtain the lock and adjust the pmiCookie
                // used for methodRT PMI counter to exclude the lock time.
                if (pmiBean != null) {
                    // d648142.2
                    long lockDuration = pmiBean.finalTime(lockStatType, lockStartTime);
                    if (lockDuration > 0) {
                        s.pmiCookie += lockDuration; // d724734
                    }
                }
            }
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "preInvoke");

        return ivEjbInstance;
    }
1343612
void renewLease(String holder) throws IOException {
    readLock();
    try {
      if (isInSafeMode()) {
        throw new SafeModeException("Cannot renew lease for " + holder, safeMode);
      }

      leaseManager.renewLease(holder);
    } finally {
      readUnlock();
    }
  }
72310
<T> T callWithRetries(Callable<T> callable, RecurringPolicy<?> recurringPolicy,
      RecurringStats retryStats, Set<Class<? extends Exception>> retryableExceptions,
      boolean recoverable, boolean logFailures) throws Exception {
    boolean recovery = retryStats != null;

    while (true) {
      try {
        return callable.call();
      } catch (Exception e) {
        ShutdownSignalException sse = extractCause(e, ShutdownSignalException.class);
        if (sse == null && logFailures && recurringPolicy != null
            && recurringPolicy.allowsAttempts())
          log.error("Invocation of {} failed.", callable, e);

        if (sse != null && (recovery || !recoverable))
          throw e;

        if (!closed) {
          try {
            // Retry on channel recovery failure or retryable exception
            boolean retryable =
                recurringPolicy != null && recurringPolicy.allowsAttempts()
                    && isRetryable(retryableExceptions, e, sse);
            long startTime = System.nanoTime();

            if (retryable) {
              if (retryStats == null) 
                retryStats = new RecurringStats(recurringPolicy);
                
              // Wait for pending recovery
              if (sse != null) {
                if (recurringPolicy.getMaxDuration() == null)
                  circuit.await();
                else if (!circuit.await(retryStats.getMaxWaitTime())) {
                  log.debug("Exceeded max wait time while waiting for {} to recover", this);
                  throw e;
                }
              }

              // Continue retries
              retryStats.incrementAttempts();
              if (!retryStats.isPolicyExceeded()) {
                long remainingWaitTime =
                    retryStats.getWaitTime().toNanos() - (System.nanoTime() - startTime);
                if (remainingWaitTime > 0)
                  retryWaiter.await(Duration.nanos(remainingWaitTime));
                continue;
              }
            }
          } catch (Throwable ignore) {
          }
        }

        throw e;
      }
    }
  }
352775
@SuppressWarnings({ "squid:S2221", "squid:S00112" })
    public <T> T runAsSystemAsTenant(final Callable<T> callable, final String tenant) {
        final SecurityContext oldContext = SecurityContextHolder.getContext();
        try {
            LOG.debug("entering system code execution");
            return tenantAware.runAsTenant(tenant, () -> {
                try {
                    setSystemContext(SecurityContextHolder.getContext());
                    return callable.call();

                } catch (final RuntimeException e) {
                    throw e;
                } catch (final Exception e) {
                    throw new RuntimeException(e);
                }
            });

        } finally {
            SecurityContextHolder.setContext(oldContext);
            LOG.debug("leaving system code execution");
        }
    }
989412
public void setThreadName (final String threadName)
  {
    if (threadName == null || threadName.trim ().length () == 0)
    {
      throw new IllegalArgumentException ("Scheduler thread name cannot be empty.");
    }

    m_sThreadName = threadName;
  }
1200089
protected void updateLockHolder(String clientId, long lockDurationMs) {
        this.clientId = clientId;
        this.timestampExpiry = System.currentTimeMillis() + lockDurationMs;
    }
494984
public OneStepDistributedRowLock<K, C> expireLockAfter(long timeout, TimeUnit unit) {
        this.timeout      = timeout;
        this.timeoutUnits = unit;
        return this;
    }
884643
private <T> Optional<T> tryWithLock(long timeout, TimeUnit unit, Supplier<T> task)
    {
        checkLockNotHeld("Lock can not be reacquired");

        boolean acquired = false;
        try {
            acquired = exclusiveLock.tryLock(timeout, unit);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        if (!acquired) {
            return Optional.empty();
        }

        Optional<T> result;
        try {
            result = Optional.of(task.get());
        }
        finally {
            try {
                try {
                    processNewSources();
                }
                finally {
                    destroyIfNecessary();
                }
            }
            finally {
                exclusiveLock.unlock();
            }
        }

        // If there are more source updates available, attempt to reacquire the lock and process them.
        // This can happen if new sources are added while we're holding the lock here doing work.
        // NOTE: this is separate duplicate code to make debugging lock reacquisition easier
        // The first condition is for processing the pending updates if this driver is still ALIVE
        // The second condition is to destroy the driver if the state is NEED_DESTRUCTION
        while (((pendingTaskSourceUpdates.get() != null && state.get() == State.ALIVE) || state.get() == State.NEED_DESTRUCTION)
                && exclusiveLock.tryLock()) {
            try {
                try {
                    processNewSources();
                }
                finally {
                    destroyIfNecessary();
                }
            }
            finally {
                exclusiveLock.unlock();
            }
        }

        return result;
    }