We synchronize on a per-site basis, but we use a separate lock
object for each site so that the process of loading a bundle for
the first time does not require blocking access to resources from
other sites.
184374
protected Object getLock (int siteId)
    {
        Object lock = null;

        synchronized (_locks) {
            lock = _locks.get(siteId);

            // create a lock object if we haven't one already
            if (lock == null) {
                _locks.put(siteId, lock = new Object());
            }
        }

        return lock;
    }
441178
function ensureLock(client, path) {
  var lock = client.lock;
  if(!(lock && !('unlocked' in lock))) {
    // Create an error so we get a stack, too.
    var err = new Error('Attempted sync step without lock.');
    log.error({client: client, err: err}, 'Client should own lock but does not for ' + path);
    return false;
  }
  return true;
}
365964
public void sync() {
		if (!validState) {
			throw new InvalidStateException();
		}
		if (useMmap) {
			syncAllMmaps();
		}
		if (fileChannel != null) {
			try {
				fileChannel.force(false);
			} catch (Exception ign) {
			}
		}
		if (callback != null) {
			callback.synched();
		}
	}
710303
function(location) {
		var deferred = new Deferred();
		this._busyWhile(deferred, messages["Loading..."]);
		this._siteClient.loadSiteConfiguration(location).then(
			function(siteConfig) {
				this._setSiteConfiguration(siteConfig);
				this.setDirty(false);
				deferred.resolve(siteConfig);
			}.bind(this),
			function(error) {
				deferred.reject(error);
			});
		return deferred;
	}
311676
def _lock(self, url: str, name: str, hash_: str):
        
        self._new_lock.append({
            'url': url,
            'name': name,
            'hash': hash_,
        })
        self._stale_files.pop(name, None)
547124
def synchronizeReplica(self,
                           replicaID,
                           transportType="esriTransportTypeUrl",
                           replicaServerGen=None,
                           returnIdsForAdds=False,
                           edits=None,
                           returnAttachmentDatabyURL=False,
                           async=False,
                           syncDirection="snapshot",
                           syncLayers="perReplica",
                           editsUploadID=None,
                           editsUploadFormat=None,
                           dataFormat="json",
                           rollbackOnFailure=True):
        
        params = {
            "f" : "json",
            "replicaID" : replicaID,
            "transportType" : transportType,
            "dataFormat" : dataFormat,
            "rollbackOnFailure" : rollbackOnFailure,
            "async" : async,
            "returnIdsForAdds": returnIdsForAdds,
            "syncDirection" : syncDirection,
            "returnAttachmentDatabyURL" : returnAttachmentDatabyURL
        }
        return
92290
@SuppressWarnings("unused")
	@Scheduled(fixedDelay = DateUtils.MILLIS_PER_MINUTE)
	public void syncSubscriptions() {
		if (!mySyncSubscriptionsSemaphore.tryAcquire()) {
			return;
		}
		try {
			doSyncSubscriptionsWithRetry();
		} finally {
			mySyncSubscriptionsSemaphore.release();
		}
	}
155942
def app
      @app || @app_build_lock.synchronize {
        @app ||= begin
          stack = default_middleware_stack
          config.middleware = build_middleware.merge_into(stack)
          config.middleware.build(endpoint)
        end
      }
    end
201719
void initializeReplQueues() throws SafeModeException {
    writeLock();
    try {
      if (isPopulatingReplQueues()) {
        NameNode.stateChangeLog.info("STATE* Safe mode is already OFF."
            + " Replication queues are initialized");
        return;
      }
      safeMode.initializeReplicationQueues();
    } finally {
      writeUnlock();
    }
  }
706291
private void lockAndRegisterReferences(ClassDescriptor cld, Object sourceObject, int lockMode, List registeredObjects) throws LockNotGrantedException
    {
        if (implicitLocking)
        {
            Iterator i = cld.getObjectReferenceDescriptors(true).iterator();
            while (i.hasNext())
            {
                ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) i.next();
                Object refObj = rds.getPersistentField().get(sourceObject);
                if (refObj != null)
                {
                    boolean isProxy = ProxyHelper.isProxy(refObj);
                    RuntimeObject rt = isProxy ? new RuntimeObject(refObj, this, false) : new RuntimeObject(refObj, this);
                    if (!registrationList.contains(rt.getIdentity()))
                    {
                        lockAndRegister(rt, lockMode, registeredObjects);
                    }
                }
            }
        }
    }
550746
public synchronized void locking(Context ctxt, ILexLocation location)
	{
		// Enter a locking state - called by thread
		waitUntilState(RunState.LOCKING, RunState.RUNNING, ctxt, location);
	}
180122
public synchronized void initPathToResourceBundleMap(List<JoinableResourceBundle> bundles) throws IOException {

		for (JoinableResourceBundle bundle : bundles) {

			// Remove bundle reference from existing mapping if exists
			removePathMappingFromPathMap(bundle);

			List<PathMapping> mappings = bundle.getMappings();
			for (PathMapping pathMapping : mappings) {
				register(pathMapping);
			}

			// Register file path mapping for linked resources
			List<FilePathMapping> fMappings = bundle.getLinkedFilePathMappings();
			for (FilePathMapping fMapping : fMappings) {
				register(fMapping);
			}
		}
	}
662140
@Override
    public boolean addSync() throws ResourceException {

        if (tc.isEntryEnabled()) {
            Tr.entry(this, tc, "addSync");
        }

        try {

            UOWCoordinator uowCoord = mcWrapper.getUOWCoordinator();
            if (uowCoord != null) {
                if (uowCoord.isGlobal()) {
                    if (mcWrapper.isConnectionSynchronizationProvider()) {
                        throw new UnsupportedOperationException("com.ibm.ws.Transaction.SynchronizationProvider");
                        /*
                         * Use the Synchronization object from the managed connection to
                         * register.
                         */
                        //Synchronization s = ((SynchronizationProvider)mcWrapper.getManagedConnection()).getSynchronization();
                        //LocationSpecificFunction.instance.getTransactionManager().registerSynchronization(uowCoord, s, EmbeddableWebSphereTransactionManager.SYNC_TIER_INNER);
                    }
                    /*
                     * This code will remain here just in case we run into this
                     * case. We should not be isEnlistmentDisabled in this code.
                     *
                     * Log a message and return, if isEnlistmentDisabled is true.
                     */
                    if (mcWrapper.isEnlistmentDisabled()) {
                        if (tc.isDebugEnabled()) {
                            Tr.debug(this, tc, "Managed connection isEnlistmentDisabled is true.");
                            Tr.debug(this, tc, "Returning without registering.");
                        }
                        if (tc.isEntryEnabled()) {
                            Tr.exit(this, tc, "addSync", false);
                        }
                        return false;
                    }
                    /*
                     * Use our XATransactionWrapper
                     */
                    // Global Transaction
                    EmbeddableWebSphereTransactionManager tranMgr = mcWrapper.pm.connectorSvc.transactionManager;
                    tranMgr.registerSynchronization(uowCoord, this);
                    mcWrapper.markLocalTransactionWrapperInUse();
                    registeredForSync = true;
                } else {
                    // Local Transaction
                    // No need to register for synchronization for unshared/LTC/res-control=Application.
                    //  Instead of cleanup being done via after completion it will either happen at close or
                    //  commit/rollback which ever happens last.  This will allow the connection to be returned
                    //  to the pool prior to the end of the LTC scope allowing better utilization of the connection.
                    boolean shareable = mcWrapper.getConnectionManager().shareable();
                    if (!shareable && !J2CUtilityClass.isContainerAtBoundary(mcWrapper.pm.connectorSvc.transactionManager)) {
                        // Register an instance of an RRS no-transaction wrapper
                        // so the TM will create an RRS NativeLocalTranasction.  The wrapper
                        // provides "empty" TransactioWrapper and Synchronization behaviors,
                        // but indicates to the TM that the LTC requires RRS support.

                        //if (tc.isEntryEnabled()) {
                        //  Tr.exit(this, tc, "addSync: returning without registering.");
                        //}
                        //return false;
                        if (this.isRRSTransactional()) {
                            ((SynchronizationRegistryUOWScope) uowCoord).registerInterposedSynchronization(
                                                                                                           new RRSNoTransactionWrapper());
                        } else {
                            if (tc.isEntryEnabled()) {
                                Tr.exit(this, tc, "addSync", "returning without registering");
                            }
                            return false;
                        }
                    } else {

                        if (mcWrapper.isConnectionSynchronizationProvider()) {
                            throw new UnsupportedOperationException("com.ibm.ws.Transaction.SynchronizationProvider");
                            /*
                             * Use the Synchronization object from the managed connection to
                             * register.
                             */
                            //Synchronization s = ((SynchronizationProvider)mcWrapper.getManagedConnection()).getSynchronization();
                            //((SynchronizationRegistryUOWScope) uowCoord).registerInterposedSynchronization(s);
                            //registeredForSync = false;
                        } else {

                            /*
                             * In order
                             * to take advantage of the new level of code in which MCWrapper has the isEnlistmentDisabled()
                             */
                            if (mcWrapper.isEnlistmentDisabled()) {
                                if (tc.isDebugEnabled()) {
                                    Tr.debug(this, tc, "Managed connection isEnlistmentDisabled is true.");
                                    Tr.debug(this, tc, "Returning without registering.");
                                }
                                if (tc.isEntryEnabled()) {
                                    Tr.exit(this, tc, "addSync", false);
                                }
                                return false;
                            }
                            ((SynchronizationRegistryUOWScope) uowCoord).registerInterposedSynchronization(this);
                            mcWrapper.markLocalTransactionWrapperInUse();
                            registeredForSync = true;
                        }

                    }
                }
            } else {
                // No transaction context.  Should never happen.
                Tr.error(tc, "NO_VALID_TRANSACTION_CONTEXT_J2CA0040", "addSync", null, mcWrapper.gConfigProps.cfName);
                throw new ResourceException("INTERNAL ERROR: No valid transaction context present");
            }

        } catch (ResourceException e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(
                                                        e,
                                                        "com.ibm.ejs.j2c.LocalTransactionWrapper.addSync",
                                                        "594",
                                                        this);
            Tr.error(tc, "REGISTER_WITH_SYNCHRONIZATION_EXCP_J2CA0026", "addSync", e, "Exception");
            throw e;
        } catch (Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(
                                                        e,
                                                        "com.ibm.ejs.j2c.LocalTransactionWrapper.addSync",
                                                        "605",
                                                        this);
            Tr.error(tc, "REGISTER_WITH_SYNCHRONIZATION_EXCP_J2CA0026", "addSync", e, "Exception");
            ResourceException re = new ResourceException("addSync: caught Exception");
            re.initCause(e);
            throw re;
        }
        if (tc.isEntryEnabled()) {
            Tr.exit(this, tc, "addSync", registeredForSync);
        }

        return registeredForSync;

    }
882905
@Override
	public void init(ResourceBundlesHandler bundler, Boolean useRandomParam, Boolean async, Boolean defer,
			String crossorigin) {
		init(bundler, DEFAULT_TYPE, useRandomParam, async, defer, crossorigin);
	}
683028
public void build(List<JoinableResourceBundle> bundlesToBuild, boolean forceWriteBundleMapping,
			StopWatch stopWatch) {

		stopProcessIfNeeded();

		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("Starting bundle processing");
		}

		notifyStartBundlingProcess();

		boolean mappingFileExists = resourceBundleHandler.isExistingMappingFile();
		boolean processBundleFlag = !config.getUseBundleMapping() || !mappingFileExists;

		// Global preprocessing
		executeGlobalPreprocessing(bundlesToBuild, processBundleFlag, stopWatch);

		for (JoinableResourceBundle bundle : bundlesToBuild) {

			stopProcessIfNeeded();

			if (stopWatch != null) {
				stopWatch.start("Processing bundle '" + bundle.getName() + "'");
			}

			if (!ThreadLocalJawrContext.isBundleProcessingAtBuildTime() && null != bundle.getAlternateProductionURL()) {
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("No bundle generated for '" + bundle.getId()
							+ "' because a production URL is defined for this bundle.");
				}
			}
			if (bundle instanceof CompositeResourceBundle) {
				joinAndStoreCompositeResourcebundle((CompositeResourceBundle) bundle);
			} else {
				joinAndStoreBundle(bundle);
			}

			if (config.getUseBundleMapping()) {
				JoinableResourceBundlePropertySerializer.serializeInProperties(bundle,
						resourceBundleHandler.getResourceType(), bundleMapping);
			}

			bundle.setDirty(false);

			if (stopWatch != null) {
				stopWatch.stop();
			}
		}

		executeGlobalPostProcessing(processBundleFlag, stopWatch);
		storeJawrBundleMapping(resourceBundleHandler.isExistingMappingFile(), true);

		// Update the watcher with the path to watch
		try {
			if (watcher != null) {
				watcher.initPathToResourceBundleMap(bundlesToBuild);
			}
		} catch (IOException e) {
			throw new BundlingProcessException(e);
		}

		notifyEndBundlingProcess();
		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("End of bundle processing");
		}

	}
966927
public void queueResource (String bundle, String resource, boolean loop)
    {
        try {
            queueURL(new URL("resource://" + bundle + "/" + resource), loop);
        } catch (MalformedURLException e) {
            log.warning("Invalid resource url.", "resource", resource, e);
        }
    }
1053247
final void cleanLocks() throws RepositoryException {
        // clean the session-scoped locks: unlock all the nodes and remove the lock tokens from the system area
        Set<String> cleanedTokens = lockManager.cleanLocks(session);
        if (lockTokens.isEmpty()) {
            return;
        }
        // clean all open-scoped locks created via this session
        for (String lockToken : lockTokens) {
            if (!cleanedTokens.contains(lockToken)) {
                ModeShapeLock lock = lockManager.findLockByToken(lockToken);
                if (lock == null) {
                    // there is no existing lock for this token (it must've been removed from somewhere else)
                    continue;
                }
                // this is an open-scoped lock created via this session for which we'll have to update the 'held' flag
                if (!lockManager.setHeldBySession(session, lockToken, false)) {
                    // Generally not expected, because if the lock exists we can always change the lock-held value to false
                    // even when it is already false ...
                    throw new LockException(JcrI18n.invalidLockToken.text(lockToken));
                }
            }
        }
        // always clean our internal map of tokens
        lockTokens.clear();
    }