/*
(non-Javadoc)
@see org.overture.vdmj.scheduler.ISchedulableThread#locking(org.overture.vdmj.runtime.Context,
org.overture.vdmj.lex.ILexLocation)
550746
public synchronized void locking(Context ctxt, ILexLocation location)
	{
		// Enter a locking state - called by thread
		waitUntilState(RunState.LOCKING, RunState.RUNNING, ctxt, location);
	}
953789
@Override
    public final boolean lockItemIfAvailable(long lockID) throws SevereMessageStoreException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "lockItemIfAvailable", Long.valueOf(lockID));

        boolean locked = false;
        if (AbstractItem.NO_LOCK_ID == lockID)
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(this, tc, "lockItemIfAvailable");
            throw new SevereMessageStoreException("invalid lockID - clashes with internal constant NO_LOCK_ID");
        }
        boolean hasBecomeNonReleasable = false;
        synchronized (this)
        {
            if (!isExpired() && isAvailable())
            {
                if (ItemLinkState.STATE_AVAILABLE == _itemLinkState)
                {
                    ListStatistics stats = getParentStatistics();
                    synchronized (stats)
                    {
                        stats.incrementLocked();
                        stats.decrementAvailable();
                    }
                }
                else
                {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                        SibTr.event(this, tc, "Invalid Item state: " + _itemLinkState);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                        SibTr.exit(this, tc, "lockItemIfAvailable");
                    throw new StateException(_itemLinkState.toString());
                }
                locked = true;
                _lockID = lockID;
                hasBecomeNonReleasable = _declareNotDiscardable(_getItemNoRestore());
                _itemLinkState = ItemLinkState.STATE_LOCKED;
            }
        }
        if (hasBecomeNonReleasable)
        {
            _declareNotReleasable();
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "lockItemIfAvailable", Boolean.valueOf(locked));
        return locked;
    }
1301778
public final void lockForReadInterruptibly(L locker) throws InterruptedException {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        if (!tryLockForRead(locker)) {
            lockForReadQueuedInterruptibly(locker, addReadWaiter());
        }
    }
455423
@Override
    public T take(final WaitStrategy.Takeable<T> t) throws InterruptedException {
        T result;

        while ((result = t.take()) == null) {
            LockSupport.parkNanos(1l);
        }

        return result;
    }
676022
public LockedInodePath lockFullInodePath(AlluxioURI uri, LockPattern lockPattern)
      throws InvalidPathException, FileDoesNotExistException {
    LockedInodePath inodePath = lockInodePath(uri, lockPattern);
    if (!inodePath.fullPathExists()) {
      inodePath.close();
      throw new FileDoesNotExistException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(uri));
    }
    return inodePath;
  }
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);
        }
    }
248415
private void lockLocalization(Locale l) throws CmsException {

        if (null == m_lockedBundleFiles.get(l)) {
            LockedFile lf = LockedFile.lockResource(m_cms, m_bundleFiles.get(l));
            m_lockedBundleFiles.put(l, lf);
        }

    }
327633
@Override
  public void lock() throws JobLockException {
    try {
      this.lock.acquire();
    } catch (Exception e) {
      throw new JobLockException("Failed to acquire lock " + this.lockPath, e);
    }
  }
905975
public void lockSession(HttpServletRequest req, HttpSession sess) {
      String isNested = (String) req.getAttribute("com.ibm.servlet.engine.webapp.dispatch_nested");
      if (isNested == null || (isNested.equalsIgnoreCase("false"))) {
    
          try {
              long syncSessionTimeOut = (long)_smc.getSerializedSessionAccessMaxWaitTime() * 1000L; //convert to millisecond
              long syncSessionTimeOutNanos = syncSessionTimeOut * 1000000L; //convert to nanosecond

              // if session exits, start locking procedures
              if (sess != null) {
                  Object lock = new Object(); //create a new lock object for this request; 
                  LinkedList ll = ((SessionData)sess).getLockList(); //gets the linked lists of lock objects for this session;
                  int llsize;
                  
                  // PK09786 BEGIN -- Always synchronize on linklist before lock to avoid deadlock 
                  synchronized (ll) {
                     ((SessionData)sess).setSessionLock(Thread.currentThread(), lock); //adds thread to WsSession locks hashtable so we know who to notify in PostInvoke
                     ll.addLast(lock);
                     llsize = ll.size();
                  }       //PK19389 when another thread is in sessionPostInvoke, trying to lock linkedlist in order to notify the thread in lock.wait()
                  if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                      LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[LOCK_SESSION], 
                      "size = " + llsize + " thread = " + Thread.currentThread().getId() + " lock = " + lock.hashCode());
                  }                  
                  if (llsize > 1) {
                      long before = System.nanoTime();
                      if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                          LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[LOCK_SESSION], "waiting...");
                      }
                      synchronized (lock) {
                          lock.wait(syncSessionTimeOut);
                      }
                      if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                          LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[LOCK_SESSION], "Done waiting.");
                      }
                      long after = System.nanoTime();

                      synchronized (ll) {
                          // if timed out
                          if ((after - syncSessionTimeOutNanos) >= before) {
                              if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                                  LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[LOCK_SESSION], "notified after wait timed out");
                              }
                              // 118672 - we want to fail if we aren't supposed to get the access session
                              if (!_smc.getAccessSessionOnTimeout()) {
                                  ll.remove(lock);
                                  LoggingUtil.SESSION_LOGGER_CORE.logp(Level.SEVERE, methodClassName, methodNames[LOCK_SESSION], "WsSessionContext.timeOut");
                                  throw new RuntimeException("Session Lock time outException");
                              }
                          }
                      }
                  }
              // PK09786 END
              }
              if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                  LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[LOCK_SESSION], sess);
              }
              //return sess;
          } catch (InterruptedException e) {
              com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.webcontainer.session.impl.HttpSessionContextImpl.lockSession", "133", this);
              LoggingUtil.SESSION_LOGGER_CORE.logp(Level.SEVERE, methodClassName, methodNames[LOCK_SESSION], "CommonMessage.exception", e);
          }
      } //close if(isNested...)
  }
152732
public static void suspendOthers(ISchedulableThread thread)
	{
		synchronized (allThreads)
		{
			for (ISchedulableThread th : allThreads)
			{
				if (!th.equals(thread))
				{
					th.setSignal(Signal.SUSPEND);
				}
			}
		}
	}
993862
private void queueActionLocked(DeltaType actionType, Object obj) {
    String id = this.keyOf(obj);

    // If object is supposed to be deleted (last event is Deleted),
    // then we should ignore Sync events, because it would result in
    // recreation of this object.
    if (actionType == DeltaType.Sync && this.willObjectBeDeletedLocked(id)) {
      return;
    }

    Deque<MutablePair<DeltaType, Object>> deltas = items.get(id);
    if (deltas == null) {
      Deque<MutablePair<DeltaType, Object>> deltaList = new LinkedList<>();
      deltaList.add(new MutablePair(actionType, obj));
      deltas = new LinkedList<>(deltaList);
    } else {
      deltas.add(new MutablePair<DeltaType, Object>(actionType, obj));
    }

    // TODO(yue9944882): Eliminate the force class casting here
    Deque<MutablePair<DeltaType, Object>> combinedDeltaList =
        combineDeltas((LinkedList<MutablePair<DeltaType, Object>>) deltas);

    boolean exist = items.containsKey(id);
    if (combinedDeltaList != null && combinedDeltaList.size() > 0) {
      if (!exist) {
        this.queue.add(id);
      }
      this.items.put(id, new LinkedList<>(combinedDeltaList));
      notEmpty.signalAll();
    } else {
      this.items.remove(id);
    }
  }
964719
public static void schedule(String threadName) {
    try (LockResource r = new LockResource(sLock)) {
      ScheduledTimer timer = sTimers.get(threadName);
      if (timer == null) {
        throw new RuntimeException("Timer for thread " + threadName + " not found.");
      }
      timer.schedule();
    }
  }
559278
public void eventLocked()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "eventLocked");

    // modify prefetching info
    synchronized (this)
    {
      RemoteDispatchableKey dkey = key.getRemoteDispatchableKey();
      RemoteQPConsumerKey ck = null;
      if (dkey instanceof RemoteQPConsumerKey)
        ck = (RemoteQPConsumerKey) dkey;

      if (ck != null)
      {
        ck.messageLocked(key);
        informedConsumerKeyThatLocked = true;
      }
    }

    // call superclass
    super.eventLocked();

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "eventLocked");
  }
575966
public void lockAndRegister(RuntimeObject rtObject, int lockMode, List registeredObjects)
    {
        lockAndRegister(rtObject, lockMode, isImplicitLocking(), registeredObjects);
    }
1204414
protected void schedule() {
    try (LockResource r = new LockResource(mLock)) {
      Preconditions.checkState(!mScheduled, "Called schedule twice without waiting for any ticks");
      mScheduled = true;
      mTickCondition.signal();
      HeartbeatScheduler.removeTimer(this);
    }
  }
295609
void lockForHandlingWork() {
        synchronized(m_lock) {
            assert m_running == false;
            m_running = true;
            m_readyOps = 0;
            m_readyOps = m_selectionKey.readyOps();      // runnable.run() doesn't accept parameters
        }
    }
276837
public Optional<LockResource> tryLockInode(Long inodeId, LockMode mode) {
    return mInodeLocks.tryGet(inodeId, mode);
  }