/** * 锁 * * @param lock 锁 * @param timeout 超时时间 * <li>>0 等待超时时间</li> * <li>=0 无限等待</li> * <li><0 无限等待</li> * @return 剩余的超时时间 * <li>>0 锁成功,timeout>0,剩余超时时间</li> * <li>0 锁成功,timeout=0</li> * <li>-1 锁成功,timeout<0</li> * */ public static long tryLock(final Lock lock, final long timeout) { long time; if (timeout > 0) { time = JSFContext.systemClock.now(); try { if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { time = timeout - (JSFContext.systemClock.now() - time); if (time > 0) { return time; }else{ lock.unlock(); } } return LOCK_FAIL; } catch (InterruptedException e) { return LOCK_FAIL; } } else { lock.lock(); return timeout == 0 ? 0 : -1; } }
/** * Processes the obligations within the effective XACML policy. * * This method waits until a read lock is obtained for the set of registered obligation handlers. * * @param context current processing context * * @throws ObligationProcessingException thrown if there is a problem evaluating an obligation */ public void processObligations(ObligationProcessingContext context) throws ObligationProcessingException { Lock readLock = rwLock.readLock(); readLock.lock(); try { Iterator<BaseObligationHandler> handlerItr = obligationHandlers.iterator(); Map<String, ObligationType> effectiveObligations = preprocessObligations(context); BaseObligationHandler handler; while (handlerItr.hasNext()) { handler = handlerItr.next(); if (effectiveObligations.containsKey(handler.getObligationId())) { handler.evaluateObligation(context, effectiveObligations.get(handler.getObligationId())); } } } finally { readLock.unlock(); } }
int count(Predicate<PeerInfo> predicate) { int numberOfConnectedPeers = 0; Lock lock = readWriteLock.readLock(); try { lock.lock(); for (PeerInfo peer : peers.values()) { if (predicate.test(peer)) { numberOfConnectedPeers++; } } } finally { lock.unlock(); } return numberOfConnectedPeers; }
@Override public Vector getChangesToInitial() { Vector ret = new Vector(); Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { for (Lecture lecture: currentSolution().getModel().variables()) { if (!ToolBox.equals(lecture.getInitialAssignment(),currentSolution().getAssignment().getValue(lecture))) { RecordedAssignment a = new RecordedAssignment(this,(Placement)lecture.getInitialAssignment(),currentSolution().getAssignment().getValue(lecture)); if (lecture.getInitialAssignment()!=null) { a.getBefore().setDetails(new ClassAssignmentDetails(this,lecture,(Placement)lecture.getInitialAssignment(),false)); } if (currentSolution().getAssignment().getValue(lecture)!=null) { a.getAfter().setDetails(new ClassAssignmentDetails(this,lecture,false)); } ret.addElement(a); } } } finally { lock.unlock(); } return ret; }
/** * Gets a registered object by its index. * * @param index the index of an object previously registered, may be null * * @return the registered object or null if no object is registered for that index */ public T get(String index) { if (index == null) { return null; } Lock readLock = rwLock.readLock(); readLock.lock(); try { StoredObjectWrapper objectWrapper = objectStore.get(index); if (objectWrapper != null) { return objectWrapper.getObject(); } return null; } finally { readLock.unlock(); } }
/** * Return the Realm with which this Container is associated. If there is * no associated Realm, return the Realm associated with our parent * Container (if any); otherwise return <code>null</code>. */ @Override public Realm getRealm() { Lock l = realmLock.readLock(); try { l.lock(); if (realm != null) return (realm); if (parent != null) return (parent.getRealm()); return null; } finally { l.unlock(); } }
@Override public Lock getDistributedLock(Object key) throws IllegalStateException { validateKey(key); lockCheckReadiness(); checkForLimitedOrNoAccess(); if (!this.scope.isGlobal()) { throw new IllegalStateException( LocalizedStrings.DistributedRegion_DISTRIBUTION_LOCKS_ARE_ONLY_SUPPORTED_FOR_REGIONS_WITH_GLOBAL_SCOPE_NOT_0 .toLocalizedString(this.scope)); } if (isLockingSuspendedByCurrentThread()) { throw new IllegalStateException( LocalizedStrings.DistributedRegion_THIS_THREAD_HAS_SUSPENDED_ALL_LOCKING_FOR_THIS_REGION .toLocalizedString()); } return new DistributedLock(key); }
@Override public Collection<Ticket> getTickets() { final Collection<Ticket> collection = new HashSet<>(); final Lock lock = this.hz.getLock(getClass().getName()); lock.lock(); try { final PagingPredicate pagingPredicate = new PagingPredicate(this.pageSize); for (Collection<Ticket> entrySet = this.registry.values(pagingPredicate); !entrySet.isEmpty(); pagingPredicate.nextPage(), entrySet = this.registry.values(pagingPredicate)) { for (final Ticket entry : entrySet) { collection.add(decodeTicket(entry)); } } } finally { lock.unlock(); } return collection; }
/** * Adds the given object to the store. Technically this method only adds the object if it does not already exist in * the store. If it does this method simply increments the reference count of the object. * * @param object the object to add to the store, may be null * * @return the index that may be used to later retrieve the object or null if the object was null */ public String put(T object) { if (object == null) { return null; } Lock writeLock = rwLock.writeLock(); writeLock.lock(); try { String index = Integer.toString(object.hashCode()); StoredObjectWrapper objectWrapper = objectStore.get(index); if (objectWrapper == null) { objectWrapper = new StoredObjectWrapper(object); objectStore.put(index, objectWrapper); } objectWrapper.incremementReferenceCount(); return index; } finally { writeLock.unlock(); } }
/** * asReadLock can be locked and unlocked */ public void testAsReadLock() throws Throwable { StampedLock sl = new StampedLock(); Lock lock = sl.asReadLock(); for (Action locker : lockLockers(lock)) { locker.run(); assertTrue(sl.isReadLocked()); assertFalse(sl.isWriteLocked()); assertEquals(1, sl.getReadLockCount()); locker.run(); assertTrue(sl.isReadLocked()); assertEquals(2, sl.getReadLockCount()); lock.unlock(); lock.unlock(); assertUnlocked(sl); } }
@Override public Vector getChangesToBest() { Vector ret = new Vector(); Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { for (Lecture lecture: currentSolution().getModel().variables()) { Placement placement = currentSolution().getAssignment().getValue(lecture); if (!ToolBox.equals(lecture.getBestAssignment(), placement)) { RecordedAssignment a = new RecordedAssignment(this,(Placement)lecture.getBestAssignment(),placement); if (lecture.getBestAssignment()!=null) { a.getBefore().setDetails(new ClassAssignmentDetails(this,lecture,(Placement)lecture.getBestAssignment(),false)); } if (placement!=null) { a.getAfter().setDetails(new ClassAssignmentDetails(this,lecture,false)); } ret.addElement(a); } } } finally { lock.unlock(); } return ret; }
/** * Creates a cleaner task based on the configuration. This is provided for * convenience. * * @param conf * @param store * @param metrics * @param cleanerTaskLock lock that ensures a serial execution of cleaner * task * @return an instance of a CleanerTask */ public static CleanerTask create(Configuration conf, SCMStore store, CleanerMetrics metrics, Lock cleanerTaskLock) { try { // get the root directory for the shared cache String location = conf.get(YarnConfiguration.SHARED_CACHE_ROOT, YarnConfiguration.DEFAULT_SHARED_CACHE_ROOT); long sleepTime = conf.getLong(YarnConfiguration.SCM_CLEANER_RESOURCE_SLEEP_MS, YarnConfiguration.DEFAULT_SCM_CLEANER_RESOURCE_SLEEP_MS); int nestedLevel = SharedCacheUtil.getCacheDepth(conf); FileSystem fs = FileSystem.get(conf); return new CleanerTask(location, sleepTime, nestedLevel, fs, store, metrics, cleanerTaskLock); } catch (IOException e) { LOG.error("Unable to obtain the filesystem for the cleaner service", e); throw new ExceptionInInitializerError(e); } }
public final void action(final MapleClient c, final byte mode, final byte type, final int selection) { if (mode != -1) { final NPCConversationManager cm = cms.get(c); if (cm == null || cm.getLastMsg() > -1) { return; } final Lock lock = c.getNPCLock(); lock.lock(); try { if (cm.pendingDisposal) { dispose(c); } else { c.setClickedNPC(); cm.getIv().invokeFunction("action", mode, type, selection); } } catch (final ScriptException | NoSuchMethodException e) { System.err.println("Error executing NPC script. NPC ID : " + cm.getNpc() + ":" + e); dispose(c); e.printStackTrace(); } finally { lock.unlock(); } } }
@Override public AssignmentPreferenceInfo getAssignmentInfo(Long classId) { Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { Lecture lecture = null; for (Lecture l: currentSolution().getModel().variables()) { if (l.getClassId().equals(classId)) { lecture = l; break; } } if (lecture==null) return null; Placement placement = (Placement)currentSolution().getAssignment().getValue(lecture); if (placement==null) return null; return new AssignmentPreferenceInfo(this,placement); } finally { lock.unlock(); } }
private String generateAvatar(String primaryName, String secondaryName) { String encoded = Hex.encodeHexString((primaryName + ":" + AvatarGenerator.version()).getBytes()); if (StringUtils.isBlank(primaryName)) primaryName = "?"; if (StringUtils.isBlank(secondaryName)) secondaryName = primaryName; File avatarFile = new File(Bootstrap.getSiteDir(), "avatars/generated/" + encoded); if (!avatarFile.exists()) { Lock avatarLock = LockUtils.getLock("generated-avatar:" + encoded); avatarLock.lock(); try { String letters = getLetter(primaryName); BufferedImage bi = AvatarGenerator.generate(letters, secondaryName); FileUtils.createDir(avatarFile.getParentFile()); ImageIO.write(bi, "PNG", avatarFile); } catch (NoSuchAlgorithmException | IOException e) { throw new RuntimeException(e); } finally { avatarLock.unlock(); } } return AVATARS_BASE_URL + "generated/" + encoded; }
@Override public ArticleForPush createReplayWeb(ArticleWebInput article, File file) throws StorageBackendException { StorageWeb db = null; Lock l = locks[2]; l.lock(); try{ db = fixedStoragePool.remove(); ArticleForPush ret = db.createReplayWeb(article, file); return ret; }finally{ if( db != null) fixedStoragePool.add(db); l.unlock(); } }
/** * Try to get a lock in the given number of milliseconds or get an exception * * @param lock the lock to try * @param timeoutMs the number of milliseconds to try * @param useCase {@link String} value which specifies description of use case when lock is needed * @throws LockTryException the exception if the time is exceeded or the thread is interrupted */ public static void tryLock(Lock lock, long timeoutMs, String useCase) throws LockTryException { boolean gotLock = false; try { gotLock = lock.tryLock(timeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // Handled } if (!gotLock) { throw new LockTryException("Failed to get lock " + lock.getClass().getSimpleName() + " for " + useCase + " in " + timeoutMs + "ms."); } }
/** {@inheritDoc} */ public EntitiesDescriptor getEntitiesDescriptor(String name) throws MetadataProviderException { Lock readLock = providerLock.readLock(); readLock.lock(); EntitiesDescriptor descriptor = null; try { for (MetadataProvider provider : providers) { log.debug("Checking child metadata provider for entities descriptor with name: {}", name); try { descriptor = provider.getEntitiesDescriptor(name); if (descriptor != null) { break; } } catch (MetadataProviderException e) { log.warn("Error retrieving metadata from provider of type {}, proceeding to next provider", provider.getClass().getName(), e); continue; } } } finally { readLock.unlock(); } return descriptor; }
ReentrantCycleDetectingLock(CycleDetectingLockFactory<ID> lockFactory, ID userLockId, Lock lockImplementation) { this.lockFactory = lockFactory; this.userLockId = Preconditions.checkNotNull(userLockId, "userLockId"); this.lockImplementation = Preconditions.checkNotNull( lockImplementation, "lockImplementation"); }
/** * Test Region.getRegionDistributedLock(), calling lock() and then unlock() */ @Test public void testRegionDistributedLockSimple() throws CacheException { final String name = this.getUniqueName(); Region r = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs()); Lock lock = r.getRegionDistributedLock(); lock.lock(); lock.unlock(); }
/** * This implementation only checks readiness and scope */ public Lock getDistributedLock(Object key) throws IllegalStateException { checkReadiness(); checkForLimitedOrNoAccess(); Scope theScope = getAttributes().getScope(); Assert.assertTrue(theScope == Scope.LOCAL); throw new IllegalStateException( LocalizedStrings.LocalRegion_ONLY_SUPPORTED_FOR_GLOBAL_SCOPE_NOT_LOCAL.toLocalizedString()); }
public void setDescription(String description) { Lock l = mBeanInfoLock.writeLock(); l.lock(); try { this.description = description; this.info = null; } finally { l.unlock(); } }
/** * Actions are notified when lock is opened or closed. Actions are called while holding state lock, so that no other threads are working with cache while these are running. * * @param stateLock Lock to hold while mutating state. * @param onOpen Action to run when the lock is opened. Action is called while holding state lock * @param onClose Action to run when the lock is closed. Action is called while holding state lock */ public LockOnDemandCrossProcessCacheAccess(String cacheDisplayName, File lockTarget, LockOptions lockOptions, FileLockManager lockManager, Lock stateLock, CacheInitializationAction initAction, Action<FileLock> onOpen, Action<FileLock> onClose) { this.cacheDisplayName = cacheDisplayName; this.lockTarget = lockTarget; this.lockOptions = lockOptions; this.lockManager = lockManager; this.stateLock = stateLock; this.initAction = initAction; this.onOpen = onOpen; this.onClose = onClose; }
/** * Add a new parameter to the set of arguments for this operation. * * @param parameter The new parameter descriptor */ public void addParameter(ParameterInfo parameter) { Lock writeLock = parametersLock.writeLock(); try { writeLock.lock(); ParameterInfo results[] = new ParameterInfo[parameters.length + 1]; System.arraycopy(parameters, 0, results, 0, parameters.length); results[parameters.length] = parameter; parameters = results; this.info = null; } finally { writeLock.unlock(); } }
public ReleasableLock(Lock lock) { this.lock = lock; boolean useHoldingThreads = false; assert (useHoldingThreads = true); if (useHoldingThreads) { holdingThreads = new ThreadLocal<>(); } else { holdingThreads = null; } }
private void signalOtherThreadsToStart( final TServer server, final Lock startLock, final Condition startCondition, final AtomicBoolean startedServing) { // A simple thread to wait until the server has started and then signal the other threads to // begin Thread t = new Thread() { @Override public void run() { do { try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.warn("Signalling thread was interuppted: " + e.getMessage()); } } while (!server.isServing()); startLock.lock(); try { startedServing.set(true); startCondition.signalAll(); } finally { startLock.unlock(); } } }; t.start(); }
@Override public SuggestionsResponse computeSuggestions(ComputeSuggestionsRequest request) { Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { return new InstructorSchedulingSuggestions(this).computeSuggestions(request); } finally { lock.unlock(); } }
@Nullable @Override public Blob get(final BlobId blobId, final boolean includeDeleted) { checkNotNull(blobId); final S3Blob blob = liveBlobs.getUnchecked(blobId); if (blob.isStale()) { Lock lock = blob.lock(); try { if (blob.isStale()) { S3BlobAttributes blobAttributes = new S3BlobAttributes(s3, getConfiguredBucket(), attributePath(blobId).toString()); boolean loaded = blobAttributes.load(); if (!loaded) { log.warn("Attempt to access non-existent blob {} ({})", blobId, blobAttributes); return null; } if (blobAttributes.isDeleted() && !includeDeleted) { log.warn("Attempt to access soft-deleted blob {} ({})", blobId, blobAttributes); return null; } blob.refresh(blobAttributes.getHeaders(), blobAttributes.getMetrics()); } } catch (IOException e) { throw new BlobStoreException(e, blobId); } finally { lock.unlock(); } } log.debug("Accessing blob {}", blobId); return blob; }
/** * Get lock with a default lease time configured in the config-dlock.properties * * @param lockType enum DLockType * @param lockTarget * @return */ public Lock gen(DLockType lockType, String lockTarget) { // pre-check Integer lease = lockConfigMap.get(lockType); Assert.notNull(lease, "unfound config for DLockType:" + lockType); return getLockInstance(lockType.name(), lockTarget, lease, TimeUnit.MILLISECONDS); }
public void testDeadLock207855() throws Exception { clearWorkDir(); final File wd = getWorkDir(); final File cache = new File (wd,"cache"); //NOI18N cache.mkdir(); IndexUtil.setCacheFolder(cache); final File root = new File (wd,"src"); //NOI18N root.mkdir(); final Lock lock = new ReentrantLock(); final CountDownLatch holdsLock = new CountDownLatch(1); final CountDownLatch inListener = new CountDownLatch(1); final FileChangeListener dl = new DeadLockListener(lock, inListener); FileUtil.addRecursiveListener(dl, cache); try { final Thread worker = new Thread() { @Override public void run() { lock.lock(); holdsLock.countDown(); try { inListener.await(); ClassIndexManager.getDefault().getUsagesQuery(Utilities.toURI(root).toURL(), true); } catch (InterruptedException ie) { Exceptions.printStackTrace(ie); } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); } finally { lock.unlock(); } } }; worker.start(); holdsLock.await(); ClassIndexManager.getDefault().getUsagesQuery(Utilities.toURI(root).toURL(), true); } finally { FileUtil.removeRecursiveListener(dl, cache); } }
@Override public AssignmentPreferenceInfo getInfo(Hint hint) { Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { return hint.getInfo(this); } finally { lock.unlock(); } }
private RowLockImpl getRowLock(Lock l) { count.incrementAndGet(); synchronized (lock) { if (usable.get()) { return new RowLockImpl(this, l); } else { return null; } } }
@VisibleForTesting void incrementBy(long offset, Instant startTimestamp, ImmutableList<String> labelValues) { Lock lock = valueLocks.get(labelValues); lock.lock(); try { values.addAndGet(labelValues, offset); valueStartTimestamps.putIfAbsent(labelValues, startTimestamp); } finally { lock.unlock(); } }
@Override public ArticleOutput getArticleWeb(String message_id, Integer id) throws StorageBackendException { StorageWeb db = null; Lock l = locks[0]; l.lock(); try{ db = fixedStoragePool.remove(); ArticleOutput ret = db.getArticleWeb(message_id, id); return ret; }finally{ if( db != null) fixedStoragePool.add(db); l.unlock(); } }
public void setType(String type) { Lock l = mBeanInfoLock.writeLock(); l.lock(); try { this.type = type; this.info = null; } finally { l.unlock(); } }
@VisibleForTesting final void reset(Instant startTimestamp, ImmutableList<String> labelValues) { Lock lock = valueLocks.get(labelValues); lock.lock(); try { this.values.put(labelValues, new MutableDistribution(distributionFitter)); this.valueStartTimestamps.put(labelValues, startTimestamp); } finally { lock.unlock(); } }
/** * Returns the lock that prevents the parent's primary from moving while active writes are in * progress. This should be locked before checking if the local bucket is primary. * * @return the lock for in-progress write operations */ Lock getParentActiveWriteLock() { if (this.parentAdvisor != null) { return this.parentAdvisor.getActiveWriteLock(); } return null; }
/** * Adds a collection of obligation handler to the list of registered handlers * * This method waits until a write lock is obtained for the set of registered obligation handlers. * * @param handlers the collection of handlers to add to the list of registered handlers. */ public void addObligationhandler(Collection<BaseObligationHandler> handlers) { if (handlers == null || handlers.isEmpty()) { return; } Lock writeLock = rwLock.writeLock(); writeLock.lock(); try { obligationHandlers.addAll(handlers); } finally { writeLock.unlock(); } }
void get() { int randomInt1 = random.nextInt() % 10; if (randomInt1 < 0) { randomInt1 = randomInt1 * (-1); } Integer integer1 = Integer.valueOf(randomInt1); Object v = null; Object expected = null; Lock lock = null; if (this.validate) { lock = map.get(integer1); lock.lock(); } try { try { logWriter.info("Key = " + integer1.longValue()); v = region1.get(integer1); if (this.validate) { expected = region2.get(integer1); } } catch (Exception e) { e.printStackTrace(); exceptionOccuredInGets = true; logWriter.severe("Exception occured in get ", e); fail(" failed during get due to " + e); } } finally { if (lock != null) { lock.unlock(); } } if (this.validate) { assertEquals(expected, v); } }
@Override protected void onFinish() { super.onFinish(); try { iWorking = true; if (currentSolution().getBestInfo()!=null) currentSolution().restoreBest(); finishBeforeSave(); if (currentSolution().getBestInfo()!=null && getProperties().getPropertyBoolean("General.Save",false)) { ProblemSaver<V, T, M> saver = getDatabaseSaver(this); Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { saver.save(); } catch (Exception e) { sLog.error("Failed to save the problem: " + e.getMessage(), e); } finally { lock.unlock(); } } if (getProperties().getPropertyBoolean("General.Unload",false)) { dispose(); } else { Progress.getInstance(currentSolution().getModel()).setStatus("Awaiting commands ..."); } } finally { iWorking = false; } }