List of usage examples for java.util.concurrent.locks Lock tryLock
boolean tryLock();
From source file:Main.java
/** * This methods blocks until the worker is done and returns the result value of the worker. * If the worker was canceled an exception will be thrown. * * @param worker The worker//from w w w . j av a 2 s . c o m * @param <T> result type of the worker * @return the result * @throws InterruptedException if the worker was canceled */ public static <T> T waitFor(Worker<T> worker) throws InterruptedException { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); lock.lock(); try { ReadOnlyBooleanProperty doneProperty = createIsDoneProperty(worker); if (doneProperty.get()) { return worker.getValue(); } else { doneProperty.addListener(e -> { boolean locked = lock.tryLock(); if (locked) { try { condition.signal(); } finally { lock.unlock(); } } else { throw new RuntimeException("Concurreny Error"); } }); condition.await(); return worker.getValue(); } } finally { lock.unlock(); } }
From source file:gridool.util.GridUtils.java
public static void accquireLock(final Lock lock, final String targetLabel, final long timeoutInSec, final int maxWaitIntSec) throws InterruptedException { if (lock.tryLock() == false) { if (lock.tryLock(timeoutInSec, TimeUnit.SECONDS) == false) { final Random rand = new Random(); if (LOG.isInfoEnabled()) { StackTraceElement[] traces = Thread.currentThread().getStackTrace(); final String traceStr = PrintUtils.toString(traces, 10); int retry = 1; do { int time = rand.nextInt(maxWaitIntSec); LOG.info("Try lock on '" + targetLabel + "' failed " + retry + " times. Sleep " + time + " seconds.\n" + traceStr); Thread.sleep(time * 1000L); retry++;//from w w w. j a va2s . c o m } while (lock.tryLock(timeoutInSec, TimeUnit.SECONDS) == false); } else { do { int time = rand.nextInt(maxWaitIntSec); Thread.sleep(time * 1000L); } while (lock.tryLock(timeoutInSec, TimeUnit.SECONDS) == false); } } } }
From source file:edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.factory.OrganizationToPublicationsForSubOrganizationsFactory.java
@Override public Model getOrCreateModel(String uri, Dataset dataset) throws MalformedQueryParametersException { Model candidateModel = ConstructedModelTracker.getModel(ConstructedModelTracker.generateModelIdentifier(uri, OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE)); if (candidateModel != null) { return candidateModel; } else {/* ww w .j a va 2 s .c om*/ Lock customLock = CustomLock.getLock(); if (customLock.tryLock()) //Acquiring lock if available to construct the model { try { ModelConstructor model = new OrganizationToPublicationsForSubOrganizationsModelConstructor(uri, dataset); Model constructedModel = model.getConstructedModel(); ConstructedModelTracker.trackModel( ConstructedModelTracker.generateModelIdentifier(uri, OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE), constructedModel); return constructedModel; } finally { customLock.unlock(); } } else { log.info("The Model construction process is going on"); return null; } } }
From source file:hudson.plugins.locksandlatches.LockWrapper.java
@Override public Environment setUp(AbstractBuild abstractBuild, Launcher launcher, BuildListener buildListener) throws IOException, InterruptedException { final List<NamedReentrantLock> backups = new ArrayList<NamedReentrantLock>(); List<LockWaitConfig> locks = new ArrayList<LockWaitConfig>(this.locks); // sort this list of locks so that we _always_ ask for the locks in order Collections.sort(locks, new Comparator<LockWaitConfig>() { public int compare(LockWaitConfig o1, LockWaitConfig o2) { return o1.getName().compareTo(o2.getName()); }/*from w w w .j a va2 s .c o m*/ }); // build the list of "real" locks final Map<String, Boolean> sharedLocks = new HashMap<String, Boolean>(); for (LockWaitConfig lock : locks) { NamedReentrantLock backupLock; do { backupLock = DESCRIPTOR.backupLocks.get(lock.getName()); if (backupLock == null) { DESCRIPTOR.backupLocks.putIfAbsent(lock.getName(), new NamedReentrantLock(lock.getName())); } } while (backupLock == null); backups.add(backupLock); sharedLocks.put(lock.getName(), lock.isShared()); } final StringBuilder locksToGet = new StringBuilder(); CollectionUtils.forAllDo(backups, new Closure() { public void execute(Object input) { locksToGet.append(((NamedReentrantLock) input).getName()).append(", "); } }); buildListener.getLogger() .println("[locks-and-latches] Locks to get: " + locksToGet.substring(0, locksToGet.length() - 2)); boolean haveAll = false; while (!haveAll) { haveAll = true; List<NamedReentrantLock> locked = new ArrayList<NamedReentrantLock>(); DESCRIPTOR.lockingLock.lock(); try { for (NamedReentrantLock lock : backups) { boolean shared = sharedLocks.get(lock.getName()); buildListener.getLogger().print("[locks-and-latches] Trying to get " + lock.getName() + " in " + (shared ? "shared" : "exclusive") + " mode... "); Lock actualLock; if (shared) { actualLock = lock.readLock(); } else { actualLock = lock.writeLock(); } if (actualLock.tryLock()) { buildListener.getLogger().println(" Success"); locked.add(lock); } else { buildListener.getLogger().println(" Failed, releasing all locks"); haveAll = false; break; } } if (!haveAll) { // release them all for (NamedReentrantLock lock : locked) { boolean shared = sharedLocks.get(lock.getName()); Lock actualLock; if (shared) { actualLock = lock.readLock(); } else { actualLock = lock.writeLock(); } actualLock.unlock(); } } } finally { DESCRIPTOR.lockingLock.unlock(); } if (!haveAll) { buildListener.getLogger() .println("[locks-and-latches] Could not get all the locks, sleeping for 1 minute..."); TimeUnit.SECONDS.sleep(60); } } buildListener.getLogger().println("[locks-and-latches] Have all the locks, build can start"); return new Environment() { @Override public boolean tearDown(AbstractBuild abstractBuild, BuildListener buildListener) throws IOException, InterruptedException { buildListener.getLogger().println("[locks-and-latches] Releasing all the locks"); for (NamedReentrantLock lock : backups) { boolean shared = sharedLocks.get(lock.getName()); Lock actualLock; if (shared) { actualLock = lock.readLock(); } else { actualLock = lock.writeLock(); } actualLock.unlock(); } buildListener.getLogger().println("[locks-and-latches] All the locks released"); return super.tearDown(abstractBuild, buildListener); } }; }
From source file:org.eclipse.hawkbit.repository.jpa.JpaRolloutManagement.java
@Override // No transaction, will be created per handled rollout @Transactional(propagation = Propagation.NEVER) public void handleRollouts() { final List<Long> rollouts = rolloutRepository.findByStatusIn(ACTIVE_ROLLOUTS); if (rollouts.isEmpty()) { return;// ww w .j av a 2s .com } final String tenant = tenantAware.getCurrentTenant(); final String handlerId = tenant + "-rollout"; final Lock lock = lockRegistry.obtain(handlerId); if (!lock.tryLock()) { return; } try { rollouts.forEach(rolloutId -> runInNewTransaction(handlerId + "-" + rolloutId, status -> executeFittingHandler(rolloutId))); } finally { lock.unlock(); } }
From source file:org.jasig.portal.portlet.container.services.PortletPreferencesServiceImpl.java
@Transactional @Override/*from w w w. j a v a 2 s .c om*/ public void store(PortletWindow plutoPortletWindow, PortletRequest portletRequest, Map<String, PortletPreference> newPreferences) throws PortletContainerException { final HttpServletRequest httpServletRequest = this.portalRequestUtils.getPortletHttpRequest(portletRequest); //Determine if the user is a guest final boolean isGuest = isGuestUser(portletRequest); //If this is a guest and no prefs are being stored just return as the rest of the method is not needed for this case if (isGuest && !(this.isStoreInEntity(portletRequest) || this.isStoreInMemory(portletRequest))) { return; } final IPortletWindow portletWindow = this.portletWindowRegistry.convertPortletWindow(httpServletRequest, plutoPortletWindow); IPortletEntity portletEntity = portletWindow.getPortletEntity(); final IPortletEntityId portletEntityId = portletEntity.getPortletEntityId(); final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition(); final PortletDefinition portletDescriptor = this.portletDefinitionRegistry .getParentPortletDescriptor(portletDefinition.getPortletDefinitionId()); //Is this CONFIG mode final boolean configMode = IPortletRenderer.CONFIG.equals(portletWindow.getPortletMode()); //Get Map of descriptor and definition preferences to check new preferences against final Map<String, PortletPreference> basePreferences = new HashMap<String, PortletPreference>(); //Add deploy preferences final List<IPortletPreference> descriptorPreferencesList = this.getDescriptorPreferences(portletDescriptor); this.addPreferencesToMap(descriptorPreferencesList, basePreferences, configMode); final Lock prefLock; if (configMode) { //In config mode we don't worry about locking prefLock = NoopLock.INSTANCE; } else { prefLock = this.portletEntityRegistry.getPortletEntityLock(httpServletRequest, portletEntityId); } //Do a tryLock firsrt so that we can warn about concurrent preference modification if it fails boolean locked = prefLock.tryLock(); try { if (!locked) { logger.warn("Concurrent portlet preferences modification by: " + portletDefinition.getFName() + " " + "This has the potential for changes to preferences to be lost. " + "This portlet should be modified to synchronize its preference modifications appropriately", new Throwable()); prefLock.lock(); locked = true; //Refresh the portlet entity that may have been changed by the thread we were blocked by if (!configMode) { portletEntity = this.portletEntityRegistry.getPortletEntity(httpServletRequest, portletEntityId); } } //Add definition preferences if not config mode if (!configMode) { final List<IPortletPreference> definitionPreferencesList = portletDefinition .getPortletPreferences(); this.addPreferencesToMap(definitionPreferencesList, basePreferences, false); } final List<IPortletPreference> preferencesList = new ArrayList<IPortletPreference>( newPreferences.size()); for (final PortletPreference internalPreference : newPreferences.values()) { //Ignore preferences with null names final String name = internalPreference.getName(); if (name == null) { throw new IllegalArgumentException("PortletPreference name cannot be null"); } //Convert to a uPortal preference class to ensure quality check and persistence works final IPortletPreference preference = new PortletPreferenceImpl(internalPreference); //If the preference exactly equals a descriptor or definition preference ignore it final PortletPreference basePreference = basePreferences.get(name); if (preference.equals(basePreference)) { continue; } //New preference, add it to the list preferencesList.add(preference); } //If in config mode store the preferences on the definition if (configMode) { portletDefinition.setPortletPreferences(preferencesList); this.portletDefinitionRegistry.updatePortletDefinition(portletDefinition); } //If not a guest or if guest prefs are shared store them on the entity else if (this.isStoreInEntity(portletRequest)) { //Update the portlet entity with the new preferences portletEntity.setPortletPreferences(preferencesList); this.portletEntityRegistry.storePortletEntity(httpServletRequest, portletEntity); } //Must be a guest and share must be off so store the prefs on the session else { //Store memory preferences this.storeSessionPreferences(portletEntityId, httpServletRequest, preferencesList); } } finally { //check if locked, needed due to slighly more complex logic around the tryLock and logging if (locked) { prefLock.unlock(); } } }
From source file:org.mule.transport.file.FileMessageReceiver.java
@Override public void poll() { try {// w w w. j ava 2 s .com List<File> files = this.listFiles(); if (logger.isDebugEnabled()) { logger.debug("Files: " + files.toString()); } Comparator<File> comparator = getComparator(); if (comparator != null) { Collections.sort(files, comparator); } for (File file : files) { if (getLifecycleState().isStopping()) { break; } // don't process directories if (file.isFile()) { Lock fileLock = lockFactory.createLock(file.getName()); if (fileLock.tryLock()) { try { String fileAbsolutePath = file.getAbsolutePath(); try { filesBeingProcessingObjectStore.store(fileAbsolutePath, fileAbsolutePath); if (logger.isDebugEnabled()) { logger.debug( String.format("Flag for $ stored successfully.", fileAbsolutePath)); } } catch (ObjectAlreadyExistsException e) { if (logger.isDebugEnabled()) { logger.debug(String.format("Flag for %s being processed is on. Skipping file.", fileAbsolutePath)); } continue; } if (file.exists()) { processFile(file); } } finally { fileLock.unlock(); } } } } } catch (Exception e) { getConnector().getMuleContext().getExceptionListener().handleException(e); } }
From source file:org.nema.medical.mint.server.processor.StudyUpdateProcessor.java
@Override public void run() { LOG.debug("Execution started."); String jobID = jobFolder.getName(); String studyUUID = studyFolder.getName(); JobInfo jobInfo = new JobInfo(); jobInfo.setId(jobID);/* w ww. j a va 2s.c o m*/ jobInfo.setStudyID(studyUUID); Lock lock = new ReentrantLock(), oldLock; oldLock = studyIdLocks.putIfAbsent(studyUUID, lock); if (oldLock != null) { LOG.debug("Lock was an existing lock."); lock = oldLock; } if (lock.tryLock()) { try { LOG.debug("Got lock, and starting process"); //Not calling mkdir on this because they better already exist File changelogRoot = new File(studyFolder, "changelog"); if (!changelogRoot.exists()) { throw new FileNotFoundException("The changelog for study uuid " + studyUUID + " does not exist, may need to do a create first."); } /* * Need to load new study information */ final StudyMetadata newStudy = StudyIO.loadStudy(jobFolder); final String typeName = newStudy.getType(); final MetadataType dataDictionary = availableTypes.get(typeName); if (dataDictionary == null) { throw new RuntimeException("Invalid study type " + typeName); } if (newStudy.getVersion() >= 0) { throw new RuntimeException("Study update data specifies a version [" + newStudy.getVersion() + "]; versions are controlled by server, not client"); } try { StorageUtil.validateStudy(newStudy, dataDictionary, jobFolder); } catch (final StudyTraversals.TraversalException e) { throw new RuntimeException("Validation of the jobs study failed", e); } final File typeFolder = new File(studyFolder, typeName); final File existingBinaryFolder = new File(typeFolder, "binaryitems"); existingBinaryFolder.mkdirs(); StudyMetadata existingStudy; try { /* * Need to load current study information */ existingStudy = StudyIO.loadStudy(typeFolder); } catch (final RuntimeException e) { /* * Do nothing, just means there is no existing study * which is fine. */ existingStudy = null; } /* * If the study versions are not the same, then this * update is for a version that is not the most recent and * should not be applied. */ if (existingStudy != null && (existingStudy.getVersion() < 0 || existingStudy.getVersion() != oldVersion)) { throw new RuntimeException( "Study update data is of a different version than the current study, " + "cannot update if versions do not match. (" + existingStudy.getVersion() + " : " + oldVersion + ")"); } /* * Need to rename the new binary files so there are no collisions * with existing data files when merging. This also means updating * the new study document. */ final int maxExistingItemNumber = StorageUtil.getHighestNumberedBinaryItem(existingBinaryFolder); StorageUtil.shiftItemIds(newStudy, jobFolder, maxExistingItemNumber + 1); /* * Write metadata update message to change log folder. */ File changelogFolder = StorageUtil.getNextChangelogDir(changelogRoot); StudyUtils.writeStudy(newStudy, changelogFolder); Collection<Integer> excludedBids = new HashSet<Integer>(); if (existingStudy != null) { /* * Need to move through the new study and look for things to exclude * and exclude them from the existing study. */ StudyUtils.applyExcludes(existingStudy, newStudy, excludedBids); } /* * Clean out excludes because excludes should not be left in * the newStudy. */ StudyUtils.removeStudyExcludes(newStudy); /* * Need to merge the study documents and renormalize the result. * This means first denormalize, then merge, then normalize the * result */ StudyUtils.denormalizeStudy(newStudy); if (existingStudy != null) { StudyUtils.denormalizeStudy(existingStudy); StudyUtils.mergeStudy(existingStudy, newStudy, excludedBids); // Get next version number existingStudy.setVersion(existingStudy.getVersion() + 1); } else { /* * If no existing study, new study becomes the existing * study. This happens when an update is done on a type that * has no data yet. */ existingStudy = newStudy; // Set to base level version existingStudy.setVersion(StudyUtils.getBaseVersion()); existingStudy.setType(typeName); } //Rename all excluded binary files to have .exclude StorageUtil.renameExcludedFiles(existingBinaryFolder, excludedBids); StudyUtils.normalizeStudy(existingStudy); /* * Need to copy into the Study folder the new study document and * binary data files. */ StudyUtils.writeStudy(existingStudy, typeFolder); StorageUtil.moveBinaryItems(jobFolder, existingBinaryFolder); FileUtils.deleteDirectory(jobFolder); //Update study DAO only if this is DICOM data; don't update study DAO for other types (DICOM is primary) if (typeName.equals("DICOM")) { MINTStudy studyData = new MINTStudy(); studyData.setID(studyUUID); studyData.setStudyInstanceUID(existingStudy.getStudyInstanceUID()); studyData.setPatientID(existingStudy.getValueForAttribute(0x00100020)); studyData.setAccessionNumber(existingStudy.getValueForAttribute(0x00080050)); // studyData.setDateTime(study.getValueForAttribute(0x00080020)); studyData.setDateTime(MINTStudy.now()); studyData.setStudyVersion(existingStudy.getVersion()); studyDAO.updateStudy(studyData); } //Update change DAO for any type Change updateInfo = new Change(); updateInfo.setId(UUID.randomUUID().toString()); updateInfo.setStudyID(studyUUID); updateInfo.setType(typeName); updateInfo.setRemoteUser(remoteUser); updateInfo.setRemoteHost(remoteHost); updateInfo.setIndex(Integer.parseInt(changelogFolder.getName())); updateInfo.setOperation(ChangeOperation.UPDATE); updateDAO.saveChange(updateInfo); jobInfo.setStatus(JobStatus.SUCCESS); jobInfo.setStatusDescription("complete"); } catch (Exception e) { jobInfo.setStatus(JobStatus.FAILED); jobInfo.setStatusDescription(e.getMessage()); LOG.error("unable to process job " + jobID, e); } finally { lock.unlock(); LOG.debug("Released lock and stopping."); } } else { jobInfo.setStatus(JobStatus.FAILED); jobInfo.setStatusDescription("unable to process job " + jobID + ", another update is current being processed on the same study."); } jobInfoDAO.saveOrUpdateJobInfo(jobInfo); }
From source file:org.orbeon.oxf.cache.MemoryCacheImpl.java
private boolean tryEvict(CacheEntry entry) { assert keyToEntryMap.containsKey(entry.key); // Obtain lock if possible final Lock lock; final boolean canEvict; if (entry.cacheable instanceof Cacheable) { lock = ((Cacheable) entry.cacheable).getEvictionLock(); canEvict = lock == null || lock.tryLock(); } else {//from ww w . j av a2 s. co m lock = null; canEvict = true; } // Only remove object if we are allowed to if (canEvict) { try { remove(entry.key, true, false); } finally { // Release lock if we got one if (lock != null) lock.unlock(); } } return canEvict; }
From source file:org.orbisgis.corejdbc.ReadTable.java
public static Collection<Integer> getSortedColumnRowIndex(Connection connection, ReadRowSet originalOrder, String table, String originalColumnName, boolean ascending, ProgressMonitor progressMonitor) throws SQLException { String quoteIdentifier = TableLocation.quoteIdentifier(originalColumnName); TableLocation tableLocation = TableLocation.parse(table); Collection<Integer> columnValues; try (Statement st = connection.createStatement()) { int rowCount = 0; try (ResultSet rs = st.executeQuery("SELECT COUNT(*) cpt from " + tableLocation.toString())) { if (rs.next()) { rowCount = rs.getInt(1); }//from w ww. j a v a 2 s .com } columnValues = new ArrayList<>(rowCount); PropertyChangeListener listener = EventHandler.create(PropertyChangeListener.class, st, "cancel"); progressMonitor.addPropertyChangeListener(ProgressMonitor.PROP_CANCEL, listener); try { int pkIndex = JDBCUtilities.getIntegerPrimaryKey(connection, tableLocation.toString()); if (pkIndex > 0) { ProgressMonitor jobProgress = progressMonitor.startTask(2); // Do not cache values // Use SQL sort DatabaseMetaData meta = connection.getMetaData(); String pkFieldName = TableLocation .quoteIdentifier(JDBCUtilities.getFieldName(meta, table, pkIndex)); String desc = ""; if (!ascending) { desc = " DESC"; } // Create a map of Row Id to Pk Value ProgressMonitor cacheProgress = jobProgress.startTask(I18N.tr("Cache primary key values"), rowCount); Map<Long, Integer> pkValueToRowId = new HashMap<>(rowCount); int rowId = 0; Lock lock = originalOrder.getReadLock(); lock.tryLock(); try { originalOrder.beforeFirst(); while (originalOrder.next()) { rowId++; pkValueToRowId.put(originalOrder.getPk(), rowId); cacheProgress.endTask(); } } finally { lock.unlock(); } // Read ordered pk values ProgressMonitor sortProgress = jobProgress.startTask(I18N.tr("Read sorted keys"), rowCount); try (ResultSet rs = st.executeQuery( "select " + pkFieldName + " from " + table + " ORDER BY " + quoteIdentifier + desc)) { while (rs.next()) { columnValues.add(pkValueToRowId.get(rs.getLong(1))); sortProgress.endTask(); } } } else { ProgressMonitor jobProgress = progressMonitor.startTask(2); //Cache values ProgressMonitor cacheProgress = jobProgress.startTask(I18N.tr("Cache table values"), rowCount); Comparable[] cache = new Comparable[rowCount]; Lock lock = originalOrder.getReadLock(); lock.tryLock(); try { originalOrder.beforeFirst(); int i = 0; final int fieldIndex = originalOrder.findColumn(originalColumnName); long time1 = 0, time2 = 0, time3 = 0, time4 = 0, time5 = 0; time5 -= System.currentTimeMillis(); while (originalOrder.next()) { time5 += System.currentTimeMillis(); time1 -= System.currentTimeMillis(); Object obj = originalOrder.getObject(fieldIndex); time1 += System.currentTimeMillis(); time2 -= System.currentTimeMillis(); if (obj != null && !(obj instanceof Comparable)) { throw new SQLException(I18N.tr("Could only sort comparable database object type")); } time2 += System.currentTimeMillis(); time3 -= System.currentTimeMillis(); cache[i++] = (Comparable) obj; time3 += System.currentTimeMillis(); time4 -= System.currentTimeMillis(); cacheProgress.endTask(); time4 += System.currentTimeMillis(); time5 -= System.currentTimeMillis(); } time5 += System.currentTimeMillis(); System.out.println("time 1:" + time1 + ";" + "time 2:" + time2 + ";" + "time 3:" + time3 + ";" + "time 4:" + time4 + ";" + "time 5:" + time5 + ";"); } finally { lock.unlock(); } ProgressMonitor sortProgress = jobProgress.startTask(I18N.tr("Sort table values"), rowCount); Comparator<Integer> comparator = new SortValueCachedComparator(cache); if (!ascending) { comparator = Collections.reverseOrder(comparator); } columnValues = new TreeSet<>(comparator); for (int i = 1; i <= rowCount; i++) { columnValues.add(i); sortProgress.endTask(); } } } finally { progressMonitor.removePropertyChangeListener(listener); } return columnValues; } }